{
  "components": {
    "responses": {
      "BadRequest": {
        "content": {
          "application/json": {
            "example": {
              "code": "ERR_3006",
              "detail": "Validation failed",
              "guidance": "入力内容を確認して再度お試しください",
              "instance": "/api/journals",
              "message": "Validation failed",
              "requestId": "req_abc123",
              "retryable": false,
              "status": 400,
              "success": false,
              "title": "Validation Error",
              "type": "https://api.soloboss.cloud/errors/ERR_3006"
            },
            "schema": {
              "$ref": "#/components/schemas/ProblemDetails"
            }
          }
        },
        "description": "Invalid request parameters or validation error"
      },
      "Conflict": {
        "content": {
          "application/json": {
            "example": {
              "code": "ERR_4003",
              "detail": "Resource already exists",
              "guidance": "ページを更新して再度お試しください",
              "instance": "/api/clients",
              "message": "Resource already exists",
              "requestId": "req_abc123",
              "retryable": true,
              "status": 409,
              "success": false,
              "title": "Conflict",
              "type": "https://api.soloboss.cloud/errors/ERR_4003"
            },
            "schema": {
              "$ref": "#/components/schemas/ProblemDetails"
            }
          }
        },
        "description": "Resource conflict (duplicate)"
      },
      "Forbidden": {
        "content": {
          "application/json": {
            "example": {
              "code": "ERR_2001",
              "detail": "You do not have permission to access this resource",
              "guidance": "管理者に連絡してください",
              "instance": "/api/reimbursement/123/approve",
              "message": "Forbidden",
              "requestId": "req_abc123",
              "retryable": false,
              "status": 403,
              "success": false,
              "title": "Forbidden",
              "type": "https://api.soloboss.cloud/errors/ERR_2001"
            },
            "schema": {
              "$ref": "#/components/schemas/ProblemDetails"
            }
          }
        },
        "description": "Authenticated user lacks permission for this resource"
      },
      "InternalServerError": {
        "content": {
          "application/json": {
            "example": {
              "code": "ERR_6001",
              "detail": "Internal server error",
              "guidance": "しばらく待ってから再度お試しください",
              "instance": "/api/journals",
              "message": "Internal server error",
              "requestId": "req_abc123",
              "retryable": true,
              "status": 500,
              "success": false,
              "title": "Internal Server Error",
              "type": "https://api.soloboss.cloud/errors/ERR_6001"
            },
            "schema": {
              "$ref": "#/components/schemas/ProblemDetails"
            }
          }
        },
        "description": "Internal server error"
      },
      "NotFound": {
        "content": {
          "application/json": {
            "example": {
              "code": "ERR_4001",
              "detail": "Resource not found",
              "guidance": "URL や対象データを確認し、一覧から選び直してください",
              "instance": "/api/journals/123",
              "message": "Resource not found",
              "requestId": "req_abc123",
              "retryable": false,
              "status": 404,
              "success": false,
              "title": "Not Found",
              "type": "https://api.soloboss.cloud/errors/ERR_4001"
            },
            "schema": {
              "$ref": "#/components/schemas/ProblemDetails"
            }
          }
        },
        "description": "Resource not found"
      },
      "TooManyRequests": {
        "content": {
          "application/json": {
            "example": {
              "code": "ERR_8001",
              "detail": "Too many requests",
              "guidance": "しばらく待ってから再度お試しください",
              "instance": "/api/ai/reconcile",
              "message": "Too many requests",
              "requestId": "req_abc123",
              "retryable": true,
              "status": 429,
              "success": false,
              "title": "Rate Limit Exceeded",
              "type": "https://api.soloboss.cloud/errors/ERR_8001"
            },
            "schema": {
              "$ref": "#/components/schemas/ProblemDetails"
            }
          }
        },
        "description": "Rate limit exceeded"
      },
      "Unauthorized": {
        "content": {
          "application/json": {
            "example": {
              "code": "ERR_1001",
              "detail": "Authentication required",
              "guidance": "ログインしてください",
              "instance": "/api/journals",
              "message": "Authentication required",
              "requestId": "req_abc123",
              "retryable": false,
              "status": 401,
              "success": false,
              "title": "Unauthorized",
              "type": "https://api.soloboss.cloud/errors/ERR_1001"
            },
            "schema": {
              "$ref": "#/components/schemas/ProblemDetails"
            }
          }
        },
        "description": "Authentication required or token invalid"
      }
    },
    "schemas": {
      "AIAnalysisStatus": {
        "description": "Status of cached AI analysis",
        "enum": [
          "active",
          "expired",
          "invalidated",
          "superseded"
        ],
        "example": "active",
        "type": "string"
      },
      "AIAnalysisType": {
        "description": "Type of AI analysis",
        "enum": [
          "categorization",
          "journal_entry",
          "document_match",
          "rule_suggestion"
        ],
        "example": "journal_entry",
        "type": "string"
      },
      "AIFeedbackRequest": {
        "properties": {
          "bank_transaction_id": {
            "format": "uuid",
            "type": "string"
          },
          "corrected_account_code": {
            "example": "6230",
            "type": "string"
          },
          "corrected_account_name": {
            "example": "通信費",
            "type": "string"
          },
          "correction_reason": {
            "example": "AWSはクラウドサービスなので通信費",
            "type": "string"
          },
          "document_id": {
            "format": "uuid",
            "type": "string"
          },
          "journal_entry_id": {
            "format": "uuid",
            "type": "string"
          },
          "original_account_code": {
            "example": "559",
            "type": "string"
          },
          "original_account_name": {
            "example": "雑費",
            "type": "string"
          },
          "original_confidence": {
            "example": 0.75,
            "type": "number"
          },
          "should_create_preference": {
            "example": true,
            "type": "boolean"
          },
          "vendor_pattern": {
            "example": "AWS",
            "type": "string"
          }
        },
        "required": [
          "journal_entry_id",
          "original_account_code",
          "corrected_account_code"
        ],
        "type": "object"
      },
      "AIImageAnalysisRequest": {
        "properties": {
          "file": {
            "description": "Image file to analyze (JPEG, JPG, PNG formats supported, max 2MB)",
            "example": "image.jpg",
            "format": "binary",
            "type": "string"
          },
          "max_tokens": {
            "description": "Maximum number of tokens to generate in the response",
            "example": 1000,
            "maximum": 16000,
            "minimum": 1,
            "type": "integer"
          },
          "model": {
            "description": "AI model to use for analysis (provider-specific)",
            "enum": [
              "gpt-4o",
              "gpt-4o-mini",
              "gpt-4-turbo",
              "gemini-1.5-flash",
              "gemini-1.5-pro",
              "claude-3-5-sonnet-20241022",
              "claude-3-5-haiku-20241022"
            ],
            "example": "gpt-4o",
            "type": "string"
          },
          "prompt": {
            "description": "Analysis prompt or question about the image",
            "example": "Describe what you see in this image and identify any text or objects",
            "maxLength": 1000,
            "type": "string"
          }
        },
        "required": [
          "file",
          "prompt"
        ],
        "type": "object"
      },
      "AIImageAnalysisResponse": {
        "description": "Standardized response for image/PDF document analysis (v4.22)",
        "properties": {
          "data": {
            "properties": {
              "content": {
                "description": "Raw AI output (may be JSON string or extracted text)",
                "example": "{\"vendor\": \"サンプル商事株式会社\", \"amount\": 550000, \"date\": \"2024-11-30\"}",
                "type": "string"
              },
              "extraction_confidence": {
                "description": "Confidence level of data extraction",
                "enum": [
                  "high",
                  "medium",
                  "low",
                  "failed"
                ],
                "example": "high",
                "type": "string"
              },
              "model": {
                "description": "Specific model used for the analysis",
                "example": "gpt-4o",
                "type": "string"
              },
              "provider": {
                "description": "AI provider used for the analysis",
                "enum": [
                  "openai",
                  "gemini",
                  "claude"
                ],
                "example": "openai",
                "type": "string"
              },
              "structured_data": {
                "description": "Parsed structured data from document (null if extraction failed)",
                "nullable": true,
                "properties": {
                  "amount": {
                    "description": "合計金額",
                    "example": 550000,
                    "nullable": true,
                    "type": "number"
                  },
                  "category": {
                    "description": "カテゴリ",
                    "example": "システム開発",
                    "nullable": true,
                    "type": "string"
                  },
                  "date": {
                    "description": "日付 (YYYY-MM-DD)",
                    "example": "2024-11-30",
                    "nullable": true,
                    "type": "string"
                  },
                  "description": {
                    "description": "摘要/内容",
                    "nullable": true,
                    "type": "string"
                  },
                  "invoice_number": {
                    "description": "請求書番号",
                    "example": "INV202411-006",
                    "nullable": true,
                    "type": "string"
                  },
                  "items": {
                    "description": "明細行",
                    "items": {
                      "properties": {
                        "amount": {
                          "description": "金額",
                          "type": "number"
                        },
                        "description": {
                          "description": "品目",
                          "type": "string"
                        },
                        "quantity": {
                          "description": "数量",
                          "type": "number"
                        },
                        "unit_price": {
                          "description": "単価",
                          "type": "number"
                        }
                      },
                      "type": "object"
                    },
                    "nullable": true,
                    "type": "array"
                  },
                  "notes": {
                    "description": "備考",
                    "nullable": true,
                    "type": "string"
                  },
                  "payment_method": {
                    "description": "支払方法",
                    "nullable": true,
                    "type": "string"
                  },
                  "subtotal": {
                    "description": "税抜金額",
                    "example": 4800000,
                    "nullable": true,
                    "type": "number"
                  },
                  "tax_amount": {
                    "description": "消費税額",
                    "example": 480000,
                    "nullable": true,
                    "type": "number"
                  },
                  "vendor": {
                    "description": "取引先/会社名",
                    "example": "サンプル商事株式会社",
                    "nullable": true,
                    "type": "string"
                  }
                },
                "type": "object"
              }
            },
            "required": [
              "content",
              "structured_data",
              "extraction_confidence",
              "provider",
              "model"
            ],
            "type": "object"
          },
          "message": {
            "example": "Image analyzed successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "AIModel": {
        "properties": {
          "capabilities": {
            "description": "Model capabilities and features",
            "example": [
              "text",
              "vision",
              "code",
              "function_calling",
              "streaming"
            ],
            "items": {
              "$ref": "#/components/schemas/ModelCapability"
            },
            "type": "array"
          },
          "contextWindow": {
            "description": "Maximum context window in tokens",
            "example": 1050000,
            "type": "integer"
          },
          "deprecated": {
            "description": "Whether model is deprecated",
            "example": false,
            "type": "boolean"
          },
          "description": {
            "description": "Model description and use cases",
            "example": "Flagship (Sep 2026): replaces GPT-5.4 at a lower price, 1.05M context ($2/$10 per MTok)",
            "type": "string"
          },
          "id": {
            "description": "Unique model identifier",
            "example": "gpt-6-sol",
            "type": "string"
          },
          "maxOutputTokens": {
            "description": "Maximum output tokens per request",
            "example": 128000,
            "type": "integer"
          },
          "name": {
            "description": "Human-readable model name",
            "example": "GPT-6 Sol",
            "type": "string"
          },
          "pricingTier": {
            "$ref": "#/components/schemas/PricingTier"
          },
          "provider": {
            "description": "Provider identifier",
            "example": "openai",
            "type": "string"
          },
          "recommended": {
            "description": "Whether model is recommended for general use",
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "id",
          "name",
          "provider",
          "description",
          "contextWindow",
          "maxOutputTokens",
          "capabilities",
          "pricingTier"
        ],
        "type": "object"
      },
      "AIPdfAnalysisRequest": {
        "properties": {
          "file": {
            "description": "PDF file to analyze (PDF format only, max 2MB)",
            "example": "financial_report_2024.pdf",
            "format": "binary",
            "type": "string"
          },
          "max_tokens": {
            "description": "Maximum number of tokens to generate in the response",
            "example": 2000,
            "maximum": 16000,
            "minimum": 1,
            "type": "integer"
          },
          "prompt": {
            "description": "Analysis prompt or question about the PDF document",
            "example": "Extract all key information from this document and summarize the main points in a structured format.",
            "maxLength": 2000,
            "type": "string"
          }
        },
        "required": [
          "file",
          "prompt",
          "max_tokens"
        ],
        "type": "object"
      },
      "AIPdfAnalysisResponse": {
        "properties": {
          "data": {
            "properties": {
              "analysis": {
                "description": "AI-generated analysis of the PDF content",
                "example": "This financial report contains quarterly earnings data for Q4 2024. Key findings include: 1) Revenue increased by 15% compared to previous quarter, 2) Operating expenses decreased by 8%, 3) Net profit margin improved to 12.5%. The document also includes detailed breakdowns of revenue by product line and geographic region.",
                "type": "string"
              },
              "metadata": {
                "properties": {
                  "apiKeySource": {
                    "description": "Source of the API key used",
                    "enum": [
                      "user_key",
                      "system_key"
                    ],
                    "example": "user_key",
                    "type": "string"
                  },
                  "filename": {
                    "description": "Original filename of the analyzed PDF",
                    "example": "financial_report_2024.pdf",
                    "type": "string"
                  },
                  "finishReason": {
                    "description": "Reason why analysis stopped",
                    "enum": [
                      "stop",
                      "length",
                      "content_filter"
                    ],
                    "example": "stop",
                    "type": "string"
                  },
                  "processingTime": {
                    "description": "Time taken to process the request in milliseconds",
                    "example": 3500,
                    "type": "number"
                  }
                },
                "type": "object"
              },
              "model": {
                "description": "Specific model used for the analysis",
                "example": "gpt-4o",
                "type": "string"
              },
              "provider": {
                "description": "AI provider used for the analysis (currently only OpenAI supported)",
                "enum": [
                  "openai"
                ],
                "example": "openai",
                "type": "string"
              },
              "usage": {
                "properties": {
                  "completionTokens": {
                    "description": "Number of tokens used in the completion",
                    "example": 280,
                    "type": "number"
                  },
                  "promptTokens": {
                    "description": "Number of tokens used in the prompt",
                    "example": 45,
                    "type": "number"
                  },
                  "totalTokens": {
                    "description": "Total tokens used in the request",
                    "example": 325,
                    "type": "number"
                  }
                },
                "type": "object"
              }
            },
            "required": [
              "analysis",
              "provider",
              "model"
            ],
            "type": "object"
          },
          "message": {
            "example": "PDF analyzed successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "AIPreference": {
        "description": "AI user preference for journal generation",
        "properties": {
          "account_code": {
            "description": "Target account code",
            "example": "6230",
            "nullable": true,
            "type": "string"
          },
          "account_name": {
            "description": "Target account name",
            "example": "通信費",
            "nullable": true,
            "type": "string"
          },
          "created_at": {
            "format": "date-time",
            "type": "string"
          },
          "description": {
            "description": "Human-readable description of the preference",
            "example": "AWS/Amazon Web Services → 通信費(6230)",
            "type": "string"
          },
          "id": {
            "description": "Unique identifier for the preference",
            "format": "uuid",
            "type": "string"
          },
          "is_active": {
            "description": "Whether the preference is active",
            "example": true,
            "type": "boolean"
          },
          "last_used_at": {
            "description": "Last time this preference was used",
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "pattern": {
            "description": "Regex pattern for matching (e.g., vendor name)",
            "example": "(?i)(amazon|aws|ｱﾏｿﾞﾝ)",
            "nullable": true,
            "type": "string"
          },
          "preference_type": {
            "$ref": "#/components/schemas/AIPreferenceType"
          },
          "priority": {
            "description": "Priority order (higher = more important)",
            "example": 0,
            "type": "integer"
          },
          "scope": {
            "$ref": "#/components/schemas/AIPreferenceScope"
          },
          "source": {
            "$ref": "#/components/schemas/AIPreferenceSource"
          },
          "tax_category": {
            "description": "Tax category for the preference",
            "example": "課税仕入10%",
            "nullable": true,
            "type": "string"
          },
          "updated_at": {
            "format": "date-time",
            "type": "string"
          },
          "usage_count": {
            "description": "Number of times this preference was applied",
            "example": 15,
            "type": "integer"
          }
        },
        "type": "object"
      },
      "AIPreferenceScope": {
        "description": "Scope of the preference (inheritance order: user > company > system)",
        "enum": [
          "user",
          "company",
          "system"
        ],
        "example": "user",
        "type": "string"
      },
      "AIPreferenceSource": {
        "description": "Source of the preference",
        "enum": [
          "user",
          "learned",
          "default",
          "system"
        ],
        "example": "user",
        "type": "string"
      },
      "AIPreferenceType": {
        "description": "Type of AI preference",
        "enum": [
          "vendor_mapping",
          "category_default",
          "tax_handling",
          "custom_rule"
        ],
        "example": "vendor_mapping",
        "type": "string"
      },
      "AIPreferencesStats": {
        "properties": {
          "active_preferences": {
            "description": "Number of active preferences",
            "example": 10,
            "type": "integer"
          },
          "learned_from_corrections": {
            "description": "Preferences auto-learned from user corrections",
            "example": 3,
            "type": "integer"
          },
          "total_preferences": {
            "description": "Total number of preferences",
            "example": 12,
            "type": "integer"
          }
        },
        "type": "object"
      },
      "AIProvider": {
        "properties": {
          "id": {
            "description": "Provider ID from AIProvider enum",
            "example": 0,
            "type": "number"
          },
          "name": {
            "description": "Human-readable provider name",
            "example": "OpenAI",
            "type": "string"
          }
        },
        "required": [
          "id",
          "name"
        ],
        "type": "object"
      },
      "AISettingsResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/AISettingsSchema",
            "description": "AI settings configuration (API keys masked)"
          },
          "message": {
            "example": "AI settings retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "AISettingsSchema": {
        "description": "AI settings configuration with conditional API key requirement. v5.5 adds use_vision_ocr for optional Vision OCR.",
        "properties": {
          "api_key": {
            "description": "API key for the selected provider (required when use_system is false)",
            "example": "sk-proj-abc123...",
            "format": "password",
            "type": "string"
          },
          "firecrawl_api_key": {
            "description": "Optional Firecrawl API key for web scraping capabilities",
            "example": "fc-abc123...",
            "format": "password",
            "type": "string"
          },
          "provider": {
            "description": "AI provider (0: OPENAI, 1: CLAUDE, 2: TOGETHER, 3: GEMINI, 4: OPENROUTER, 5: FIRECRAWL)",
            "enum": [
              0,
              1,
              2,
              3,
              4,
              5
            ],
            "example": 0,
            "type": "integer"
          },
          "selected_model": {
            "description": "Selected AI model identifier for the provider",
            "example": "gpt-4",
            "type": "string"
          },
          "use_system": {
            "description": "Whether to use system AI settings or custom user settings",
            "example": false,
            "type": "boolean"
          },
          "use_vision_ocr": {
            "default": false,
            "description": "v5.5: Enable AI Vision OCR for PDF/image analysis. Default: false (uses server-side pdfjs text extraction which is faster and more accurate for Japanese). Enable for scanned/image-based documents.",
            "example": false,
            "type": "boolean"
          }
        },
        "required": [
          "use_system",
          "provider",
          "selected_model"
        ],
        "type": "object"
      },
      "AISettingsUpdateResponse": {
        "properties": {
          "data": {
            "example": "AI settings updated successfully",
            "type": "string"
          },
          "message": {
            "example": "AI settings updated successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "AITextGenerationRequest": {
        "properties": {
          "max_tokens": {
            "description": "Maximum number of tokens to generate in the response",
            "example": 500,
            "maximum": 16000,
            "minimum": 1,
            "type": "integer"
          },
          "message": {
            "description": "User message or input to generate text for",
            "example": "Explain the benefits of renewable energy in 3 bullet points.",
            "maxLength": 5000,
            "type": "string"
          },
          "model": {
            "description": "AI model to use for text generation (provider-specific)",
            "enum": [
              "gpt-4o",
              "gpt-4o-mini",
              "gpt-5.2",
              "gpt-5.1",
              "gpt-5-mini",
              "gemini-1.5-flash",
              "gemini-1.5-pro",
              "gemini-2.5-flash",
              "gemini-2.5-pro",
              "claude-3-5-sonnet-20241022",
              "claude-3-5-haiku-20241022",
              "claude-sonnet-4-20250514"
            ],
            "example": "gpt-4o",
            "type": "string"
          },
          "prompt": {
            "description": "System prompt or instruction for the AI model",
            "example": "You are a helpful assistant that provides concise and accurate responses.",
            "maxLength": 2000,
            "type": "string"
          },
          "temperature": {
            "description": "Controls randomness in the output (0.0 = deterministic, 1.0 = very creative)",
            "example": 0.7,
            "maximum": 1,
            "minimum": 0,
            "type": "number"
          },
          "thinking_budget": {
            "description": "Gemini thinking budget in tokens: used as-is on Gemini 2.x; on Gemini 3.x (which rejects budgets) mapped to a thinking level (<=2048 low, <=8192 medium, else high). 0 = least thinking the model allows.",
            "example": 1000,
            "maximum": 10000,
            "minimum": 0,
            "type": "integer"
          }
        },
        "required": [
          "prompt",
          "message"
        ],
        "type": "object"
      },
      "AITextGenerationResponse": {
        "properties": {
          "data": {
            "properties": {
              "content": {
                "description": "AI-generated text content",
                "example": "• Renewable energy reduces greenhouse gas emissions and helps combat climate change\n• It provides energy independence and reduces reliance on fossil fuel imports\n• Long-term cost savings through lower operational costs and stable energy prices",
                "type": "string"
              },
              "metadata": {
                "properties": {
                  "apiKeySource": {
                    "description": "Source of the API key used",
                    "enum": [
                      "user_key",
                      "system_key"
                    ],
                    "example": "user_key",
                    "type": "string"
                  },
                  "finishReason": {
                    "description": "Reason why text generation stopped",
                    "enum": [
                      "stop",
                      "length",
                      "content_filter"
                    ],
                    "example": "stop",
                    "type": "string"
                  },
                  "processingTime": {
                    "description": "Time taken to process the request in milliseconds",
                    "example": 1800,
                    "type": "number"
                  }
                },
                "type": "object"
              },
              "model": {
                "description": "Specific model used for text generation",
                "example": "gpt-4o",
                "type": "string"
              },
              "provider": {
                "description": "AI provider used for text generation",
                "enum": [
                  "openai",
                  "gemini",
                  "claude"
                ],
                "example": "openai",
                "type": "string"
              },
              "usage": {
                "properties": {
                  "completionTokens": {
                    "description": "Number of tokens used in the completion",
                    "example": 85,
                    "type": "number"
                  },
                  "promptTokens": {
                    "description": "Number of tokens used in the prompt",
                    "example": 35,
                    "type": "number"
                  },
                  "totalTokens": {
                    "description": "Total tokens used in the request",
                    "example": 120,
                    "type": "number"
                  }
                },
                "type": "object"
              }
            },
            "required": [
              "content",
              "provider",
              "model"
            ],
            "type": "object"
          },
          "message": {
            "example": "Text generated successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "Account": {
        "properties": {
          "category": {
            "description": "Account category",
            "example": "販売費及び一般管理費",
            "type": "string"
          },
          "code": {
            "description": "Account code",
            "example": "6100",
            "type": "string"
          },
          "id": {
            "description": "Account ID",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "name": {
            "description": "Account name in Japanese",
            "example": "旅費交通費",
            "type": "string"
          },
          "nameEn": {
            "description": "Account name in English",
            "example": "Travel & Transport",
            "type": "string"
          },
          "type": {
            "description": "Account type",
            "example": "expense",
            "type": "string"
          }
        },
        "required": [
          "id",
          "code",
          "name",
          "type"
        ],
        "type": "object"
      },
      "AccountInfo": {
        "properties": {
          "code": {
            "description": "Account code",
            "example": "6100",
            "type": "string"
          },
          "id": {
            "description": "Account ID",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "name": {
            "description": "Account name in Japanese",
            "example": "旅費交通費",
            "type": "string"
          },
          "type": {
            "description": "Account type",
            "example": "expense",
            "type": "string"
          }
        },
        "required": [
          "id",
          "code",
          "name",
          "type"
        ],
        "type": "object"
      },
      "AccountLedgerSummary": {
        "properties": {
          "account_code": {
            "description": "Account code for reference",
            "example": "1001",
            "type": "string"
          },
          "account_id": {
            "description": "Account unique identifier",
            "example": "456e7890-f12a-34b5-c678-901234567890",
            "format": "uuid",
            "type": "string"
          },
          "account_name": {
            "description": "Account name in Japanese",
            "example": "現金",
            "type": "string"
          },
          "account_type": {
            "description": "Account type classification",
            "enum": [
              "asset",
              "liability",
              "equity",
              "revenue",
              "expense"
            ],
            "example": "asset",
            "type": "string"
          },
          "closing_balance": {
            "description": "Closing balance at end of period (期末残高)",
            "example": 450000,
            "format": "decimal",
            "type": "number"
          },
          "net_change": {
            "description": "Net change during period (純増減)",
            "example": 300000,
            "format": "decimal",
            "type": "number"
          },
          "normal_side": {
            "description": "Normal balance side for this account type",
            "enum": [
              "debit",
              "credit"
            ],
            "example": "debit",
            "type": "string"
          },
          "opening_balance": {
            "description": "Opening balance at start of period (期首残高). Balance-sheet accounts: every posted line before the period. Revenue / expense: the fiscal year to date only (0 when the period starts on the FY start). 利益剰余金 adds the prior-year profit, so openings balance. A period crossing an FY boundary walks on continuously.",
            "example": 150000,
            "format": "decimal",
            "type": "number"
          },
          "total_credits": {
            "description": "Total credit transactions in period (貸方合計)",
            "example": 200000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "total_debits": {
            "description": "Total debit transactions in period (借方合計)",
            "example": 500000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "transaction_count": {
            "description": "Number of transactions in period",
            "example": 15,
            "minimum": 0,
            "type": "integer"
          }
        },
        "required": [
          "account_id",
          "account_code",
          "account_name",
          "account_type",
          "normal_side",
          "opening_balance",
          "total_debits",
          "total_credits",
          "closing_balance",
          "net_change",
          "transaction_count"
        ],
        "type": "object"
      },
      "AccountListResponse": {
        "properties": {
          "data": {
            "items": {
              "$ref": "#/components/schemas/Account"
            },
            "type": "array"
          },
          "message": {
            "example": "Accounts retrieved successfully",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "AccountResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/Account"
          },
          "message": {
            "example": "Account retrieved successfully",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "AccountType": {
        "description": "Japanese bank account type",
        "enum": [
          "普通",
          "当座"
        ],
        "example": "普通",
        "type": "string"
      },
      "AccountingConfig": {
        "properties": {
          "accounting_method": {
            "description": "Accounting method (0: Tax Exclusive 税抜, 1: Tax Inclusive 税込)",
            "enum": [
              0,
              1
            ],
            "example": 0,
            "type": "integer"
          },
          "consumption_tax_method": {
            "description": "Consumption tax calculation method (0: General 一般課税, 1: Simplified 簡易課税, 2: Special 20% 特例20%, 3: Two-Percent Special 2割特例)",
            "enum": [
              0,
              1,
              2,
              3
            ],
            "example": 0,
            "type": "integer"
          },
          "created_at": {
            "description": "Creation timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "declaration_type": {
            "description": "Tax declaration type (0: Blue Tax 青色申告, 1: White Tax 白色申告)",
            "enum": [
              0,
              1
            ],
            "example": 0,
            "type": "integer"
          },
          "depreciation_method": {
            "description": "Depreciation method (1: Straight Line 定額法, 2: Declining Balance 定率法, 3: Old Straight Line 旧定額法, 4: Old Declining Balance 旧定率法)",
            "enum": [
              1,
              2,
              3,
              4
            ],
            "example": 1,
            "type": "integer"
          },
          "has_exempt_period": {
            "description": "Has tax exemption period (免税期間)",
            "example": false,
            "type": "boolean"
          },
          "has_tax_payment_special_provision": {
            "description": "Has special provision for tax payment (納税猶予特例)",
            "example": false,
            "type": "boolean"
          },
          "id": {
            "description": "Accounting configuration unique identifier",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "is_deleted": {
            "description": "Soft deletion flag",
            "example": false,
            "type": "boolean"
          },
          "tax_calculation": {
            "description": "Tax calculation basis (0: Accrual 発生主義, 1: Cash 現金主義)",
            "enum": [
              0,
              1
            ],
            "example": 0,
            "type": "integer"
          },
          "taxation_type": {
            "description": "Taxation type (0: General Individual 一般個人, 1: General Proportional 一般比例, 2: Simplified 簡易, 3: Exempt 免税)",
            "enum": [
              0,
              1,
              2,
              3
            ],
            "example": 0,
            "type": "integer"
          },
          "updated_at": {
            "description": "Last update timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "user_id": {
            "description": "User identifier",
            "example": "789e0123-e45b-67c8-d901-234567890123",
            "format": "uuid",
            "type": "string"
          }
        },
        "required": [
          "id",
          "user_id",
          "created_at",
          "updated_at"
        ],
        "type": "object"
      },
      "AccountingConfigResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/AccountingConfig"
          },
          "message": {
            "example": "Accounting config retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "AccountingConfigUpdateResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/AccountingConfig"
          },
          "message": {
            "example": "Accounting config updated successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "AccountingHealthResponse": {
        "properties": {
          "accountingEquationOk": {
            "description": "Accounting equation check passed",
            "example": true,
            "type": "boolean"
          },
          "cashBalanceSources": {
            "description": "Dual cash balance: journal-derived vs bank-statement-derived (v3.1)",
            "properties": {
              "bankStatement": {
                "description": "Sum of latest balance per configured bank account (JPY)",
                "example": 36370114,
                "type": "integer"
              },
              "gap": {
                "description": "Math.abs(bank - journal)",
                "example": 12557298,
                "type": "integer"
              },
              "gapDirection": {
                "description": "Which balance is higher (balanced if gap <= 1)",
                "enum": [
                  "journal_higher",
                  "bank_higher",
                  "balanced"
                ],
                "example": "journal_higher",
                "type": "string"
              },
              "journalDerived": {
                "description": "Cash from GL accounts 101+102 (JPY)",
                "example": 48927412,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "checkedAt": {
            "example": "2026-01-25T01:49:13.100Z",
            "format": "date-time",
            "type": "string"
          },
          "errorCount": {
            "description": "Number of critical errors",
            "example": 0,
            "type": "integer"
          },
          "healthStatus": {
            "$ref": "#/components/schemas/AccountingHealthStatus"
          },
          "journalCompleteness": {
            "description": "How many bank transactions have been processed into journal entries (v3.1)",
            "properties": {
              "completionRate": {
                "description": "processedCount/total * 100",
                "example": 3.06,
                "type": "number"
              },
              "journalizationRate": {
                "description": "journalizedCount/total * 100",
                "example": 2.53,
                "type": "number"
              },
              "journalizedCount": {
                "description": "matched + partially_matched only (have journal entries)",
                "example": 34,
                "type": "integer"
              },
              "processedCount": {
                "description": "matched + partially_matched + excluded",
                "example": 41,
                "type": "integer"
              },
              "totalSourceTransactions": {
                "description": "Same as reconciliation.total",
                "example": 1342,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "reconciliation": {
            "description": "Reconciliation progress across all bank transactions (v3.1)",
            "properties": {
              "completionRate": {
                "description": "processedCount/total * 100 (2 decimals)",
                "example": 3.06,
                "type": "number"
              },
              "excluded": {
                "description": "Intentionally excluded (no journal needed)",
                "example": 7,
                "type": "integer"
              },
              "lastCheckedAt": {
                "description": "When this data was computed",
                "format": "date-time",
                "type": "string"
              },
              "matched": {
                "description": "Fully matched to journal entries",
                "example": 34,
                "type": "integer"
              },
              "partiallyMatched": {
                "description": "Partially matched",
                "example": 0,
                "type": "integer"
              },
              "pending": {
                "description": "Awaiting reconciliation",
                "example": 1301,
                "type": "integer"
              },
              "suspense": {
                "description": "In suspense (needs investigation)",
                "example": 0,
                "type": "integer"
              },
              "total": {
                "description": "Total non-duplicate bank transactions",
                "example": 1342,
                "type": "integer"
              },
              "unbooked": {
                "description": "Bank rows with no journal entry yet, per direction (BL-1167) — the cause the 帳簿 vs 銀行 note\nnames, with its count. Same predicate as the 未仕訳 count on GET /api/bank-statements (deleted_at IS NULL,\nis_duplicate = false, journal_entry_id IS NULL), read through `end_date` when given. Unlike\n`unjournalizedDeposits` / `unjournalizedWithdrawals` it does not read reconciliation_status: a pending row can\ncarry a journal entry and a matched one can lack it. Absent when the read failed.",
                "properties": {
                  "depositCount": {
                    "example": 0,
                    "type": "integer"
                  },
                  "depositTotal": {
                    "description": "JPY",
                    "example": 0,
                    "type": "integer"
                  },
                  "withdrawalCount": {
                    "example": 7,
                    "type": "integer"
                  },
                  "withdrawalTotal": {
                    "description": "JPY",
                    "example": 1512126,
                    "type": "integer"
                  }
                },
                "required": [
                  "withdrawalCount",
                  "withdrawalTotal",
                  "depositCount",
                  "depositTotal"
                ],
                "type": "object"
              },
              "unjournalizedDeposits": {
                "description": "Total pending deposit amount (JPY)",
                "example": 37855477,
                "type": "integer"
              },
              "unjournalizedWithdrawals": {
                "description": "Total pending withdrawal amount (JPY)",
                "example": 6320982,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "totalIssues": {
            "description": "Total number of issues detected",
            "example": 6,
            "type": "integer"
          },
          "totals": {
            "properties": {
              "assets": {
                "example": 5153122.64,
                "format": "decimal",
                "type": "number"
              },
              "equity": {
                "example": 0,
                "format": "decimal",
                "type": "number"
              },
              "expenses": {
                "example": 5311302.98,
                "format": "decimal",
                "type": "number"
              },
              "liabilities": {
                "example": 724652.62,
                "format": "decimal",
                "type": "number"
              },
              "netIncome": {
                "example": 4428470.02,
                "format": "decimal",
                "type": "number"
              },
              "revenue": {
                "example": 9739773,
                "format": "decimal",
                "type": "number"
              },
              "totalCredit": {
                "example": 20902513.98,
                "format": "decimal",
                "type": "number"
              },
              "totalDebit": {
                "example": 20902513.98,
                "format": "decimal",
                "type": "number"
              }
            },
            "type": "object"
          },
          "trialBalanceOk": {
            "description": "Trial balance check passed",
            "example": true,
            "type": "boolean"
          },
          "warningCount": {
            "description": "Number of warnings",
            "example": 6,
            "type": "integer"
          }
        },
        "required": [
          "healthStatus",
          "totalIssues",
          "errorCount",
          "warningCount",
          "trialBalanceOk",
          "accountingEquationOk",
          "totals",
          "checkedAt"
        ],
        "type": "object"
      },
      "AccountingHealthStatus": {
        "description": "Overall accounting health status",
        "enum": [
          "healthy",
          "warning",
          "critical"
        ],
        "example": "warning",
        "type": "string"
      },
      "AccountingImportEntry": {
        "properties": {
          "balanced": {
            "type": "boolean"
          },
          "creditTotal": {
            "type": "integer"
          },
          "date": {
            "description": "YYYYMMDD（読めない日付は null）",
            "nullable": true,
            "type": "integer"
          },
          "debitTotal": {
            "type": "integer"
          },
          "description": {
            "type": "string"
          },
          "kind": {
            "enum": [
              "regular",
              "closing",
              "opening"
            ],
            "type": "string"
          },
          "lines": {
            "items": {
              "$ref": "#/components/schemas/AccountingImportLine"
            },
            "type": "array"
          },
          "rawDate": {
            "type": "string"
          },
          "rowNumbers": {
            "items": {
              "type": "integer"
            },
            "type": "array"
          },
          "status": {
            "enum": [
              "ready",
              "error",
              "already_imported"
            ],
            "type": "string"
          }
        },
        "required": [
          "rowNumbers",
          "date",
          "kind",
          "lines",
          "debitTotal",
          "creditTotal",
          "balanced",
          "status"
        ],
        "type": "object"
      },
      "AccountingImportLine": {
        "properties": {
          "accountCode": {
            "type": "string"
          },
          "accountName": {
            "type": "string"
          },
          "amount": {
            "minimum": 0,
            "type": "integer"
          },
          "qualifiedInvoice": {
            "description": "true = 適格請求書, false = 経過措置 80% / 70%",
            "nullable": true,
            "type": "boolean"
          },
          "rate": {
            "enum": [
              "standard_10",
              "reduced_8",
              "non_taxable",
              "tax_exempt",
              "outside_scope",
              null
            ],
            "nullable": true,
            "type": "string"
          },
          "recognized": {
            "description": "false = 税区分を自動で対応付けできなかった（元の文字列のまま）",
            "type": "boolean"
          },
          "side": {
            "enum": [
              "debit",
              "credit"
            ],
            "type": "string"
          },
          "subAccountName": {
            "type": "string"
          },
          "taxAmount": {
            "nullable": true,
            "type": "integer"
          },
          "taxCategoryRaw": {
            "description": "インポート元の税区分（そのまま）",
            "type": "string"
          },
          "taxCode": {
            "description": "1 課税10% · 2 軽減8% · 3 非課税 · 4 不課税 · 5 国外/対象外",
            "nullable": true,
            "type": "integer"
          }
        },
        "required": [
          "side",
          "accountCode",
          "accountName",
          "amount",
          "taxCategoryRaw",
          "recognized"
        ],
        "type": "object"
      },
      "AccountingImportPreview": {
        "properties": {
          "alreadyImportedCount": {
            "description": "すでに取り込み済みの仕訳の件数（実行時はスキップ）",
            "type": "integer"
          },
          "detectedSourceType": {
            "enum": [
              "yayoi",
              "freee",
              "moneyforward",
              "kaikeioh",
              "generic",
              null
            ],
            "nullable": true,
            "type": "string"
          },
          "entries": {
            "description": "複合仕訳ごとの取込予定（エラーを先頭に、最大 500 件）",
            "items": {
              "$ref": "#/components/schemas/AccountingImportEntry"
            },
            "type": "array"
          },
          "entriesTruncated": {
            "type": "boolean"
          },
          "entryCount": {
            "type": "integer"
          },
          "errorEntryCount": {
            "type": "integer"
          },
          "externalAccounts": {
            "items": {
              "properties": {
                "code": {
                  "type": "string"
                },
                "name": {
                  "type": "string"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "failedRows": {
            "type": "integer"
          },
          "formatInfo": {
            "properties": {
              "columnCount": {
                "type": "integer"
              },
              "dateFormat": {
                "type": "string"
              },
              "detectedHeaders": {
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              "encoding": {
                "type": "string"
              },
              "expectedHeaders": {
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              "hasHeaderRow": {
                "type": "boolean"
              },
              "inputKind": {
                "enum": [
                  "csv",
                  "tsv",
                  "xlsx",
                  "paste"
                ],
                "type": "string"
              }
            },
            "type": "object"
          },
          "journalEntries": {
            "deprecated": true,
            "description": "旧 FE 向け: 外部勘定科目を1行ずつ並べた互換リスト。新しい FE は entries / externalAccounts を読む",
            "items": {
              "type": "object"
            },
            "type": "array"
          },
          "readyEntryCount": {
            "type": "integer"
          },
          "rowErrors": {
            "items": {
              "$ref": "#/components/schemas/AccountingImportRowError"
            },
            "type": "array"
          },
          "sourceType": {
            "enum": [
              "yayoi",
              "freee",
              "moneyforward",
              "kaikeioh",
              "generic"
            ],
            "type": "string"
          },
          "successfulRows": {
            "type": "integer"
          },
          "totalRows": {
            "type": "integer"
          },
          "unmappedAccounts": {
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "warnings": {
            "items": {
              "type": "string"
            },
            "type": "array"
          }
        },
        "required": [
          "sourceType",
          "entries",
          "entryCount",
          "readyEntryCount",
          "errorEntryCount",
          "alreadyImportedCount",
          "externalAccounts",
          "unmappedAccounts",
          "rowErrors",
          "warnings",
          "formatInfo"
        ],
        "type": "object"
      },
      "AccountingImportResult": {
        "properties": {
          "alreadyImportedCount": {
            "type": "integer"
          },
          "errorEntryCount": {
            "type": "integer"
          },
          "fixedAssetsCreated": {
            "type": "integer"
          },
          "importBatchId": {
            "description": "仕訳番号 IMP-<batch>-<hash> の batch 部分（12桁16進）",
            "nullable": true,
            "type": "string"
          },
          "journalEntriesCreated": {
            "type": "integer"
          },
          "linesCreated": {
            "type": "integer"
          },
          "skippedRecords": {
            "type": "integer"
          },
          "warnings": {
            "items": {
              "type": "string"
            },
            "type": "array"
          }
        },
        "required": [
          "journalEntriesCreated",
          "skippedRecords",
          "alreadyImportedCount",
          "warnings"
        ],
        "type": "object"
      },
      "AccountingImportRowError": {
        "properties": {
          "column": {
            "type": "string"
          },
          "message": {
            "type": "string"
          },
          "row": {
            "description": "元データの行番号（0 = ファイル全体）",
            "type": "integer"
          },
          "severity": {
            "enum": [
              "error",
              "warning"
            ],
            "type": "string"
          },
          "value": {
            "type": "string"
          }
        },
        "required": [
          "row",
          "column",
          "value",
          "message",
          "severity"
        ],
        "type": "object"
      },
      "AccountingSettings": {
        "properties": {
          "autoPostJournals": {
            "description": "Whether journal entries are automatically posted to general ledger after generation",
            "example": true,
            "type": "boolean"
          },
          "description": {
            "description": "Japanese description of current mode for UI display",
            "example": "自動転記モード: 仕訳は確認後自動的に元帳に転記されます",
            "type": "string"
          },
          "mode": {
            "description": "Current accounting workflow mode",
            "enum": [
              "auto",
              "manual"
            ],
            "example": "auto",
            "type": "string"
          },
          "pendingDraftsCount": {
            "description": "Number of draft journal entries awaiting posting",
            "example": 0,
            "minimum": 0,
            "type": "integer"
          }
        },
        "required": [
          "autoPostJournals",
          "mode",
          "description",
          "pendingDraftsCount"
        ],
        "type": "object"
      },
      "AccountingSettingsResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/AccountingSettings"
          },
          "message": {
            "example": "Accounting settings retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "AccountsResponse": {
        "properties": {
          "count": {
            "description": "Number of accounts returned",
            "example": 45,
            "type": "integer"
          },
          "data": {
            "items": {
              "$ref": "#/components/schemas/Account"
            },
            "type": "array"
          },
          "filters": {
            "properties": {
              "category": {
                "example": "all",
                "type": "string"
              },
              "type": {
                "example": "expense",
                "type": "string"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "勘定科目を取得しました",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data",
          "count",
          "filters"
        ],
        "type": "object"
      },
      "AchievementDefinition": {
        "description": "Achievement definition with color (v4.70)",
        "properties": {
          "category": {
            "example": "onboarding",
            "type": "string"
          },
          "color": {
            "description": "Semantic color derived from category",
            "example": "green",
            "type": "string"
          },
          "description": {
            "properties": {
              "en": {
                "example": "Logged in for the first time",
                "type": "string"
              },
              "ja": {
                "example": "初めてログインしました",
                "type": "string"
              }
            },
            "type": "object"
          },
          "icon": {
            "example": "👋",
            "type": "string"
          },
          "id": {
            "example": "first_login",
            "type": "string"
          },
          "name": {
            "properties": {
              "en": {
                "example": "First Step",
                "type": "string"
              },
              "ja": {
                "example": "初めの一歩",
                "type": "string"
              }
            },
            "type": "object"
          },
          "thresholds": {
            "description": "[bronze, silver, gold, platinum] thresholds",
            "items": {
              "type": "integer"
            },
            "nullable": true,
            "type": "array"
          },
          "xp": {
            "description": "XP reward for single-tier achievements",
            "nullable": true,
            "type": "integer"
          }
        },
        "type": "object"
      },
      "AchievementProgressResponse": {
        "properties": {
          "achievement_id": {
            "type": "string"
          },
          "current_progress": {
            "type": "integer"
          },
          "earned": {
            "type": "boolean"
          },
          "new_tier": {
            "enum": [
              "bronze",
              "silver",
              "gold",
              "platinum"
            ],
            "nullable": true,
            "type": "string"
          },
          "previous_tier": {
            "enum": [
              "bronze",
              "silver",
              "gold",
              "platinum"
            ],
            "nullable": true,
            "type": "string"
          },
          "xp_awarded": {
            "nullable": true,
            "type": "integer"
          }
        },
        "type": "object"
      },
      "AckRow": {
        "description": "One finding acknowledgment (working paper). Mirrors AckRow in finding-acknowledgment.service.ts; camelCase on the wire.",
        "properties": {
          "actorId": {
            "format": "uuid",
            "type": "string"
          },
          "checkRule": {
            "example": "OFFICER_COMP_NON_CONSTANT",
            "type": "string"
          },
          "createdAt": {
            "format": "date-time",
            "type": "string"
          },
          "findingSnapshot": {
            "description": "The finding as acknowledged (type, name, severity, legalBasis, details)",
            "properties": {
              "details": {
                "nullable": true,
                "type": "string"
              },
              "legalBasis": {
                "nullable": true,
                "type": "string"
              },
              "name": {
                "type": "string"
              },
              "severity": {
                "type": "string"
              },
              "type": {
                "type": "string"
              }
            },
            "type": "object"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "reason": {
            "description": "確認理由",
            "type": "string"
          },
          "revokeReason": {
            "nullable": true,
            "type": "string"
          },
          "revokedAt": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          }
        },
        "required": [
          "id",
          "checkRule",
          "reason",
          "findingSnapshot",
          "actorId",
          "revokedAt",
          "revokeReason",
          "createdAt"
        ],
        "type": "object"
      },
      "ActionCompletionResponse": {
        "properties": {
          "data": {
            "properties": {
              "actionId": {
                "format": "uuid",
                "type": "string"
              },
              "completedAt": {
                "format": "date-time",
                "nullable": true,
                "type": "string"
              },
              "isDone": {
                "example": true,
                "type": "boolean"
              },
              "systemReminderId": {
                "example": "system-withholding-tax-slip-2026",
                "type": "string"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Action marked as done",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ActivityStats": {
        "properties": {
          "activities_by_type": {
            "example": {
              "document_view": 500,
              "page_visit": 800
            },
            "type": "object"
          },
          "date_range": {
            "properties": {
              "earliest": {
                "format": "date-time",
                "nullable": true,
                "type": "string"
              },
              "latest": {
                "format": "date-time",
                "nullable": true,
                "type": "string"
              }
            },
            "type": "object"
          },
          "errors_count": {
            "example": 5,
            "type": "integer"
          },
          "most_recent_activity": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "sessions_count": {
            "example": 25,
            "type": "integer"
          },
          "total_activities": {
            "example": 1500,
            "type": "integer"
          }
        },
        "type": "object"
      },
      "AddBackupEmailRequest": {
        "properties": {
          "email": {
            "description": "Backup email address (must be different from primary)",
            "example": "backup@example.com",
            "format": "email",
            "type": "string"
          }
        },
        "required": [
          "email"
        ],
        "type": "object"
      },
      "AddFilesToGroupRequest": {
        "properties": {
          "file_ids": {
            "example": [
              "550e8400-e29b-41d4-a716-446655440000"
            ],
            "items": {
              "format": "uuid",
              "type": "string"
            },
            "minItems": 1,
            "type": "array"
          }
        },
        "required": [
          "file_ids"
        ],
        "type": "object"
      },
      "AddTransactionRequest": {
        "properties": {
          "amount": {
            "description": "Transaction amount",
            "example": 3000000,
            "type": "number"
          },
          "creditAccount": {
            "description": "Credit account",
            "example": "資本金",
            "type": "string"
          },
          "debitAccount": {
            "description": "Debit account",
            "example": "現金及び預金",
            "type": "string"
          },
          "description": {
            "description": "Optional description",
            "type": "string"
          },
          "metadata": {
            "description": "Additional metadata",
            "type": "object"
          },
          "name": {
            "description": "Transaction name",
            "example": "資本金設立",
            "type": "string"
          },
          "templateId": {
            "description": "Transaction template ID",
            "example": "capital-investment",
            "type": "string"
          }
        },
        "required": [
          "templateId",
          "name",
          "amount",
          "debitAccount",
          "creditAccount"
        ],
        "type": "object"
      },
      "AdjustmentType": {
        "description": "Type of tax adjustment result",
        "enum": [
          "還付",
          "追加徴収",
          "精算なし"
        ],
        "example": "還付",
        "type": "string"
      },
      "AdvisorChatResponse": {
        "properties": {
          "actionItems": {
            "items": {
              "properties": {
                "action": {
                  "example": "家事按分の割合を計算する",
                  "type": "string"
                },
                "deadline": {
                  "format": "date-time",
                  "nullable": true,
                  "type": "string"
                },
                "estimatedTime": {
                  "example": "30分",
                  "type": "string"
                },
                "id": {
                  "type": "string"
                },
                "priority": {
                  "enum": [
                    "urgent",
                    "high",
                    "medium",
                    "low"
                  ],
                  "type": "string"
                }
              },
              "type": "object"
            },
            "nullable": true,
            "type": "array"
          },
          "answer": {
            "example": "はい、自宅の電気代は経費にできます。ただし、「家事按分」という方法で、事業用と私用を分ける必要があります。",
            "type": "string"
          },
          "clarifications": {
            "description": "Up to 3 suggested clarification questions in Japanese (v5.15)",
            "example": [
              "個人事業主としての税金の種類について知りたいですか？",
              "確定申告の方法について知りたいですか？",
              "節税対策について知りたいですか？"
            ],
            "items": {
              "type": "string"
            },
            "maxItems": 3,
            "nullable": true,
            "type": "array"
          },
          "confidence": {
            "enum": [
              "high",
              "medium",
              "low"
            ],
            "example": "high",
            "type": "string"
          },
          "disclaimer": {
            "description": "Mandatory professional-advice disclaimer (v5.17 — 税理士法 §52/§53 / 弁護士法 §72 / 社労士法 §27 compliance). Frontend MUST render this text beside the AI response.",
            "properties": {
              "longHref": {
                "description": "Path to the public-facing long-form disclaimer document.",
                "example": "/legal/ai-disclaimer",
                "type": "string"
              },
              "text": {
                "description": "Role-aware disclaimer copy to render beside the AI response.",
                "example": "AIによる一般的な情報提供であり、税理士・弁護士・社労士による個別の専門アドバイスではありません。 個別の申告・税額計算は税理士へのご相談が必要です（税理士法第52条）。",
                "type": "string"
              },
              "version": {
                "description": "Versioned disclaimer key — bumping it invalidates all existing user acknowledgments.",
                "example": "v1-2026-05-03",
                "type": "string"
              }
            },
            "required": [
              "version",
              "text",
              "longHref"
            ],
            "type": "object"
          },
          "followUpQuestions": {
            "example": [
              "家事按分の計算方法は？",
              "どのくらいの割合で経費にできますか？"
            ],
            "items": {
              "type": "string"
            },
            "nullable": true,
            "type": "array"
          },
          "legalBasis": {
            "items": {
              "properties": {
                "law": {
                  "example": "所得税法第45条",
                  "type": "string"
                },
                "section": {
                  "example": "家事関連費",
                  "type": "string"
                },
                "summary": {
                  "example": "家事関連費に関する規定",
                  "type": "string"
                }
              },
              "type": "object"
            },
            "nullable": true,
            "type": "array"
          },
          "needs_clarification": {
            "description": "True when the AI detected an ambiguous question and is requesting clarification (v5.15)",
            "example": true,
            "nullable": true,
            "type": "boolean"
          },
          "relatedTopics": {
            "example": [
              "自宅兼事務所",
              "按分計算",
              "必要経費"
            ],
            "items": {
              "type": "string"
            },
            "nullable": true,
            "type": "array"
          },
          "warnings": {
            "example": [
              "按分割合には合理的な根拠が必要です"
            ],
            "items": {
              "type": "string"
            },
            "nullable": true,
            "type": "array"
          }
        },
        "required": [
          "answer",
          "confidence",
          "disclaimer"
        ],
        "type": "object"
      },
      "AdvisorDisclaimerStatus": {
        "description": "Status of the user's acknowledgment of the canonical AI professional-advice disclaimer.",
        "properties": {
          "acknowledgedAt": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "acknowledgedVersion": {
            "example": "v1-2026-05-03",
            "nullable": true,
            "type": "string"
          },
          "currentVersion": {
            "example": "v1-2026-05-03",
            "type": "string"
          },
          "isCurrent": {
            "description": "True iff the user has already acknowledged the current canonical version.",
            "type": "boolean"
          },
          "longHref": {
            "example": "/legal/ai-disclaimer",
            "type": "string"
          }
        },
        "required": [
          "currentVersion",
          "isCurrent",
          "longHref"
        ],
        "type": "object"
      },
      "AdvisorMessage": {
        "properties": {
          "message": {
            "example": "🎉 5件中5件は問題なし！",
            "type": "string"
          },
          "plain": {
            "example": "5件中5件は問題なし！",
            "type": "string"
          }
        },
        "type": "object"
      },
      "AdvisorRole": {
        "description": "Advisor persona role (v5.14)",
        "enum": [
          "accounting",
          "tax",
          "legal",
          "business",
          "general"
        ],
        "example": "accounting",
        "type": "string"
      },
      "Advisory": {
        "properties": {
          "acknowledgment": {
            "allOf": [
              {
                "$ref": "#/components/schemas/AdvisoryAcknowledgment"
              }
            ],
            "nullable": true
          },
          "action": {
            "type": "string"
          },
          "consequence": {
            "nullable": true,
            "type": "string"
          },
          "contentVersion": {
            "example": "2026-10-01.1",
            "type": "string"
          },
          "deadline": {
            "type": "string"
          },
          "decision": {
            "description": "confirm = a deciding fact is missing; the owner or the 税理士 decides",
            "enum": [
              "applies",
              "confirm"
            ],
            "type": "string"
          },
          "disclaimer": {
            "type": "string"
          },
          "facts": {
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "groupKey": {
            "description": "Advisories sharing it render as one card",
            "type": "string"
          },
          "key": {
            "description": "finding_acknowledgments.check_rule for this case",
            "example": "ADV:foreign-royalty-withholding:je:1db1df83-ac4a-4971-b600-ec42a0ba907f",
            "type": "string"
          },
          "memoTemplate": {
            "description": "摘要 template for a foreign payment",
            "nullable": true,
            "type": "string"
          },
          "questions": {
            "description": "Books advisories (ADR-0015): what to ask the 税理士",
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "ruleId": {
            "enum": [
              "foreign-royalty-withholding",
              "foreign-treaty-form-before-payment",
              "foreign-service-abroad-not-domestic-source",
              "foreign-personal-services-in-japan",
              "foreign-payment-record-keeping",
              "domestic-individual-fee-withholding",
              "domestic-fee-payment-record",
              "ct-foreign-transaction-out-of-scope",
              "ct-reverse-charge-digital-services",
              "ct-consumer-digital-services-invoice",
              "stamp-duty-ukeoi-contract",
              "freelance-act-terms-and-60-days",
              "contract-copyright-default-ownership",
              "contract-disguised-subcontracting",
              "construction-in-progress",
              "capital-vs-repair",
              "asset-in-service-date",
              "asset-input-tax",
              "lease-initial-costs",
              "sales-on-receipt",
              "tax-inclusive-purchase-split",
              "tax-inclusive-sales-split",
              "asset-expensed-before-service",
              "depreciation-register-tie",
              "deferred-asset-schedule",
              "year-end-tax-provisions",
              "restored-voided-entry",
              "claim-receipt-mismatch"
            ],
            "type": "string"
          },
          "severity": {
            "enum": [
              "warning",
              "info"
            ],
            "type": "string"
          },
          "sources": {
            "items": {
              "$ref": "#/components/schemas/AdvisorySource"
            },
            "type": "array"
          },
          "target": {
            "$ref": "#/components/schemas/AdvisoryTarget"
          },
          "title": {
            "type": "string"
          },
          "unverified": {
            "description": "Shown as 「確認中」",
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "what": {
            "type": "string"
          }
        },
        "required": [
          "key",
          "ruleId",
          "contentVersion",
          "severity",
          "decision",
          "title",
          "what",
          "action",
          "deadline",
          "consequence",
          "sources",
          "unverified",
          "disclaimer",
          "target",
          "groupKey",
          "facts",
          "memoTemplate",
          "acknowledgment"
        ],
        "type": "object"
      },
      "AdvisoryAcknowledgment": {
        "properties": {
          "actorId": {
            "format": "uuid",
            "type": "string"
          },
          "createdAt": {
            "format": "date-time",
            "type": "string"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "reason": {
            "type": "string"
          }
        },
        "required": [
          "id",
          "reason",
          "actorId",
          "createdAt"
        ],
        "type": "object"
      },
      "AdvisorySource": {
        "properties": {
          "title": {
            "type": "string"
          },
          "url": {
            "example": "https://www.nta.go.jp/taxes/shiraberu/taxanswer/gensen/2884.htm",
            "type": "string"
          },
          "verifiedOn": {
            "description": "The date the page was loaded and checked",
            "example": "2026-10-01",
            "type": "string"
          }
        },
        "required": [
          "url",
          "title",
          "verifiedOn"
        ],
        "type": "object"
      },
      "AdvisoryTarget": {
        "properties": {
          "id": {
            "type": "string"
          },
          "kind": {
            "enum": [
              "counterparty",
              "agreement",
              "journal_entry",
              "bank_transaction",
              "company",
              "expense"
            ],
            "type": "string"
          },
          "label": {
            "type": "string"
          }
        },
        "required": [
          "kind",
          "id",
          "label"
        ],
        "type": "object"
      },
      "AlertLevel": {
        "description": "Alert severity level for business insights",
        "enum": [
          "info",
          "warning",
          "critical",
          "success"
        ],
        "example": "warning",
        "type": "string"
      },
      "AllProviderModelsResponse": {
        "properties": {
          "data": {
            "properties": {
              "anthropic": {
                "$ref": "#/components/schemas/ProviderModelsResult"
              },
              "fetchedAt": {
                "description": "ISO timestamp of the combined fetch",
                "example": "2026-03-11T12:00:00.000Z",
                "format": "date-time",
                "type": "string"
              },
              "openai": {
                "$ref": "#/components/schemas/ProviderModelsResult"
              },
              "vertex": {
                "$ref": "#/components/schemas/ProviderModelsResult"
              }
            },
            "required": [
              "openai",
              "anthropic",
              "vertex",
              "fetchedAt"
            ],
            "type": "object"
          },
          "message": {
            "example": "Provider models retrieved successfully",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "AllProvidersResponse": {
        "properties": {
          "data": {
            "properties": {
              "providers": {
                "description": "List of all providers with their models",
                "items": {
                  "$ref": "#/components/schemas/ProviderInfo"
                },
                "type": "array"
              },
              "totalModels": {
                "description": "Total number of models across all providers",
                "example": 68,
                "type": "integer"
              },
              "totalProviders": {
                "description": "Total number of providers",
                "example": 6,
                "type": "integer"
              }
            },
            "required": [
              "providers",
              "totalProviders",
              "totalModels"
            ],
            "type": "object"
          },
          "message": {
            "example": "AI providers and models retrieved successfully",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "AllReferenceData": {
        "properties": {
          "_meta": {
            "$ref": "#/components/schemas/ReferenceDataMeta"
          },
          "accounts": {
            "description": "Chart of accounts from database",
            "items": {
              "$ref": "#/components/schemas/Account"
            },
            "type": "array"
          },
          "depreciationMethods": {
            "description": "Depreciation methods with formulas",
            "items": {
              "$ref": "#/components/schemas/EnumItem"
            },
            "type": "array"
          },
          "documentTypes": {
            "description": "Document types with workflow information",
            "items": {
              "$ref": "#/components/schemas/EnumItem"
            },
            "type": "array"
          },
          "expenseCategories": {
            "description": "Expense categories with account codes",
            "items": {
              "$ref": "#/components/schemas/EnumItem"
            },
            "type": "array"
          },
          "expenseReportStatuses": {
            "description": "Expense report statuses with next actions",
            "items": {
              "$ref": "#/components/schemas/EnumItem"
            },
            "type": "array"
          },
          "fiscalPeriodStatuses": {
            "description": "Fiscal period statuses",
            "items": {
              "$ref": "#/components/schemas/EnumItem"
            },
            "type": "array"
          },
          "fixedAssetClassifications": {
            "description": "Fixed asset classifications with useful life",
            "items": {
              "$ref": "#/components/schemas/EnumItem"
            },
            "type": "array"
          },
          "journalEntryStatuses": {
            "description": "Journal entry statuses with editability",
            "items": {
              "$ref": "#/components/schemas/EnumItem"
            },
            "type": "array"
          },
          "payeeTypes": {
            "description": "Payee types with withholding requirements",
            "items": {
              "$ref": "#/components/schemas/EnumItem"
            },
            "type": "array"
          },
          "paymentMethods": {
            "description": "Payment methods with validation rules",
            "items": {
              "$ref": "#/components/schemas/EnumItem"
            },
            "type": "array"
          },
          "reconciliationStatuses": {
            "description": "Reconciliation statuses with colors",
            "items": {
              "$ref": "#/components/schemas/EnumItem"
            },
            "type": "array"
          },
          "reminderTypes": {
            "description": "Reminder types with frequencies",
            "items": {
              "$ref": "#/components/schemas/EnumItem"
            },
            "type": "array"
          },
          "taxTypes": {
            "description": "Tax types with rates",
            "items": {
              "$ref": "#/components/schemas/EnumItem"
            },
            "type": "array"
          },
          "withholdingCategories": {
            "description": "Withholding tax categories with rates",
            "items": {
              "$ref": "#/components/schemas/EnumItem"
            },
            "type": "array"
          }
        },
        "required": [
          "expenseCategories",
          "documentTypes",
          "paymentMethods",
          "taxTypes",
          "withholdingCategories",
          "payeeTypes",
          "fiscalPeriodStatuses",
          "reconciliationStatuses",
          "expenseReportStatuses",
          "fixedAssetClassifications",
          "depreciationMethods",
          "journalEntryStatuses",
          "reminderTypes",
          "accounts",
          "_meta"
        ],
        "type": "object"
      },
      "AllReferenceDataResponse": {
        "properties": {
          "_cacheHint": {
            "properties": {
              "description": {
                "example": "This data is static and can be cached for up to 1 hour",
                "type": "string"
              },
              "maxAge": {
                "example": 3600,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "data": {
            "$ref": "#/components/schemas/AllReferenceData"
          },
          "message": {
            "example": "参照データを取得しました",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "AmountRange": {
        "properties": {
          "max": {
            "description": "Maximum amount",
            "example": 20000,
            "format": "decimal",
            "type": "number"
          },
          "min": {
            "description": "Minimum amount",
            "example": 10000,
            "format": "decimal",
            "type": "number"
          }
        },
        "required": [
          "min",
          "max"
        ],
        "type": "object"
      },
      "AnalyzeResponse": {
        "properties": {
          "classification": {
            "properties": {
              "path": {
                "enum": [
                  "CORP_EMPLOYEE",
                  "CORP_OFFICER",
                  "CORP_DEEMED_OFFICER_RISK",
                  "SOLE_PROP_BLUE_SENJUSHA",
                  "SOLE_PROP_BLUE_OTHER",
                  "SOLE_PROP_WHITE_SENJUSHA",
                  "SOLE_PROP_WHITE_OTHER",
                  "VISA_BLOCKED"
                ],
                "type": "string"
              },
              "severity": {
                "enum": [
                  "ok",
                  "warn",
                  "block"
                ],
                "type": "string"
              }
            },
            "type": "object"
          },
          "optimize": {
            "properties": {
              "recommended_scenario": {
                "type": "string"
              },
              "salary_sweep": {
                "items": {
                  "type": "object"
                },
                "type": "array"
              },
              "scenarios": {
                "items": {
                  "type": "object"
                },
                "type": "array"
              }
            },
            "type": "object"
          },
          "wall_report": {
            "properties": {
              "binding_wall": {
                "nullable": true,
                "type": "string"
              },
              "walls": {
                "items": {
                  "properties": {
                    "headroom_yen": {
                      "type": "integer"
                    },
                    "key": {
                      "type": "string"
                    },
                    "status": {
                      "enum": [
                        "safe",
                        "approaching",
                        "breached"
                      ],
                      "type": "string"
                    },
                    "threshold_yen": {
                      "type": "integer"
                    }
                  },
                  "type": "object"
                },
                "type": "array"
              }
            },
            "type": "object"
          }
        },
        "type": "object"
      },
      "AnalyzeTransactionRequest": {
        "properties": {
          "amount": {
            "description": "Transaction amount",
            "type": "number"
          },
          "bankAccountName": {
            "description": "Bank account name for context",
            "type": "string"
          },
          "date": {
            "description": "Transaction date YYYY-MM-DD",
            "format": "date",
            "type": "string"
          },
          "description": {
            "description": "Bank transaction description",
            "type": "string"
          },
          "isDeposit": {
            "description": "Whether this is a deposit (income)",
            "type": "boolean"
          }
        },
        "required": [
          "description",
          "amount",
          "isDeposit",
          "date"
        ],
        "type": "object"
      },
      "AnalyzeTransactionResponse": {
        "properties": {
          "alternativeLinkageTypes": {
            "items": {
              "properties": {
                "confidence": {
                  "type": "number"
                },
                "type": {
                  "$ref": "#/components/schemas/LinkageType"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "confidence": {
            "description": "AI confidence score 0-1",
            "maximum": 1,
            "minimum": 0,
            "type": "number"
          },
          "isRecurring": {
            "description": "Whether this appears to be a recurring transaction",
            "type": "boolean"
          },
          "reasoning": {
            "description": "Japanese explanation of suggestion",
            "type": "string"
          },
          "recurringPattern": {
            "properties": {
              "frequency": {
                "enum": [
                  "weekly",
                  "monthly",
                  "quarterly",
                  "annual"
                ],
                "type": "string"
              },
              "lastOccurrence": {
                "type": "string"
              },
              "occurrenceCount": {
                "type": "integer"
              }
            },
            "type": "object"
          },
          "suggestedAccountCode": {
            "type": "string"
          },
          "suggestedAccountName": {
            "type": "string"
          },
          "suggestedDocuments": {
            "items": {
              "properties": {
                "documentId": {
                  "format": "uuid",
                  "type": "string"
                },
                "documentType": {
                  "type": "string"
                },
                "matchReason": {
                  "type": "string"
                },
                "matchScore": {
                  "type": "number"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "suggestedLinkageType": {
            "$ref": "#/components/schemas/LinkageType"
          },
          "suggestedTaxCategory": {
            "type": "string"
          }
        },
        "type": "object"
      },
      "AnomalyDetectionRequest": {
        "properties": {
          "company_id": {
            "description": "Company ID to analyze for anomalies",
            "example": "comp_123456",
            "type": "string"
          },
          "end_date": {
            "description": "End date for anomaly detection period",
            "example": "2024-01-31",
            "format": "date",
            "type": "string"
          },
          "start_date": {
            "description": "Start date for anomaly detection period",
            "example": "2024-01-01",
            "format": "date",
            "type": "string"
          }
        },
        "required": [
          "start_date",
          "end_date",
          "company_id"
        ],
        "type": "object"
      },
      "AnomalyDetectionResponse": {
        "properties": {
          "data": {
            "properties": {
              "analysis_period": {
                "properties": {
                  "end_date": {
                    "example": "2024-01-31",
                    "format": "date",
                    "type": "string"
                  },
                  "start_date": {
                    "example": "2024-01-01",
                    "format": "date",
                    "type": "string"
                  }
                },
                "type": "object"
              },
              "anomalies": {
                "items": {
                  "properties": {
                    "anomaly_id": {
                      "example": "anom_123456",
                      "type": "string"
                    },
                    "confidence_score": {
                      "example": 0.95,
                      "type": "number"
                    },
                    "description": {
                      "example": "Unusually large transaction detected",
                      "type": "string"
                    },
                    "detected_at": {
                      "example": "2024-01-15T10:30:00.000Z",
                      "format": "date-time",
                      "type": "string"
                    },
                    "severity": {
                      "enum": [
                        "low",
                        "medium",
                        "high"
                      ],
                      "example": "high",
                      "type": "string"
                    },
                    "type": {
                      "example": "unusual_transaction",
                      "type": "string"
                    }
                  },
                  "type": "object"
                },
                "type": "array"
              },
              "total_anomalies": {
                "example": 3,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Anomaly detection completed successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "type": "object"
      },
      "ApiKeyDeleteResponse": {
        "properties": {
          "data": {
            "example": "API key has been permanently removed from your account",
            "type": "string"
          },
          "message": {
            "example": "API key removed successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ApiKeyStatusResponse": {
        "properties": {
          "data": {
            "properties": {
              "hasApiKey": {
                "description": "Whether the user has an API key stored",
                "example": true,
                "type": "boolean"
              },
              "isValid": {
                "description": "Whether the stored API key is valid",
                "example": true,
                "type": "boolean"
              },
              "lastUsed": {
                "description": "When the API key was last used",
                "example": "2024-01-15T10:30:00.000Z",
                "format": "date-time",
                "nullable": true,
                "type": "string"
              }
            },
            "required": [
              "hasApiKey"
            ],
            "type": "object"
          },
          "message": {
            "example": "API key status retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ApiKeyUpdateResponse": {
        "properties": {
          "data": {
            "example": "API key has been securely stored and validated",
            "type": "string"
          },
          "message": {
            "example": "API key updated successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ApplyExchangeRateRequest": {
        "properties": {
          "exchange_rate_id": {
            "description": "Exchange rate identifier to apply",
            "example": "789e0123-e45b-67c8-d901-234567890123",
            "format": "uuid",
            "type": "string"
          },
          "expense_id": {
            "description": "Expense identifier to apply exchange rate to",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          }
        },
        "required": [
          "expense_id",
          "exchange_rate_id"
        ],
        "type": "object"
      },
      "ApplyTemplateRequest": {
        "properties": {
          "amount": {
            "description": "Transaction amount (overrides template default)",
            "example": 5000,
            "type": "number"
          },
          "description": {
            "description": "Optional description (overrides template default)",
            "example": "東京駅→大阪駅 新幹線代",
            "type": "string"
          },
          "entry_date": {
            "description": "Entry date in YYYYMMDD format",
            "example": 20251205,
            "type": "integer"
          }
        },
        "required": [
          "entry_date",
          "amount"
        ],
        "type": "object"
      },
      "ApportionmentOverriddenLine": {
        "description": "A 課税仕入れ the owner set to credit nothing; listed so it can be cleared.",
        "properties": {
          "accountCode": {
            "nullable": true,
            "type": "string"
          },
          "accountName": {
            "nullable": true,
            "type": "string"
          },
          "amountIncTax": {
            "type": "integer"
          },
          "description": {
            "nullable": true,
            "type": "string"
          },
          "entryNumber": {
            "nullable": true,
            "type": "string"
          },
          "journalEntryId": {
            "type": "string"
          },
          "lineId": {
            "format": "uuid",
            "type": "string"
          },
          "nationalTaxAtFull": {
            "description": "National tax the line would credit at 100%",
            "type": "integer"
          },
          "note": {
            "nullable": true,
            "type": "string"
          },
          "purchaseDate": {
            "example": 20260706,
            "type": "integer"
          },
          "reason": {
            "enum": [
              "residential_rental_building",
              "invoice_not_held",
              "other_period"
            ],
            "type": "string"
          },
          "taxRate": {
            "enum": [
              "10%",
              "8%"
            ],
            "type": "string"
          }
        },
        "required": [
          "lineId",
          "amountIncTax",
          "reason",
          "nationalTaxAtFull"
        ],
        "type": "object"
      },
      "ApportionmentOverview": {
        "properties": {
          "adjustmentAssets": {
            "items": {
              "properties": {
                "accountName": {
                  "nullable": true,
                  "type": "string"
                },
                "amountIncTax": {
                  "type": "integer"
                },
                "description": {
                  "nullable": true,
                  "type": "string"
                },
                "isHighValueAsset": {
                  "type": "boolean"
                },
                "lineId": {
                  "type": "string"
                },
                "messageJa": {
                  "type": "string"
                },
                "purchaseDate": {
                  "type": "integer"
                },
                "subjectToThirdYearAdjustment": {
                  "type": "boolean"
                }
              },
              "required": [
                "lineId",
                "amountIncTax",
                "subjectToThirdYearAdjustment",
                "messageJa"
              ],
              "type": "object"
            },
            "type": "array"
          },
          "election": {
            "properties": {
              "electedAt": {
                "format": "date-time",
                "nullable": true,
                "type": "string"
              },
              "electedBy": {
                "nullable": true,
                "type": "string"
              },
              "method": {
                "enum": [
                  "individual",
                  "proportional",
                  null
                ],
                "nullable": true,
                "type": "string"
              }
            },
            "required": [
              "method"
            ],
            "type": "object"
          },
          "filedMethodConflict": {
            "description": "The period’s filed 修正申告 state different 30条2項 methods (BL-773). The recorded method is the latest amendment’s; show the conflict, not the pick.",
            "type": "boolean"
          },
          "isFiled": {
            "type": "boolean"
          },
          "lines": {
            "items": {
              "$ref": "#/components/schemas/ApportionmentReviewLine"
            },
            "type": "array"
          },
          "lock": {
            "description": "消法30条5項 — 一括比例配分方式 binds every period starting through lockedThrough.",
            "properties": {
              "adoptedFrom": {
                "nullable": true,
                "type": "integer"
              },
              "individualBlocked": {
                "type": "boolean"
              },
              "lockedThrough": {
                "nullable": true,
                "type": "integer"
              },
              "reasonJa": {
                "nullable": true,
                "type": "string"
              }
            },
            "required": [
              "individualBlocked"
            ],
            "type": "object"
          },
          "methodEditable": {
            "description": "False once a filed return recorded 個別対応 / 一括比例 (final). True for an unfiled period, or a filed one with no recorded method.",
            "type": "boolean"
          },
          "overriddenLines": {
            "items": {
              "$ref": "#/components/schemas/ApportionmentOverriddenLine"
            },
            "type": "array"
          },
          "pendingProportionalPeriodStarts": {
            "items": {
              "type": "integer"
            },
            "type": "array"
          },
          "period": {
            "properties": {
              "fiscalYear": {
                "example": 2026,
                "type": "integer"
              },
              "periodEnd": {
                "example": 20260815,
                "type": "integer"
              },
              "periodStart": {
                "example": 20260516,
                "type": "integer"
              }
            },
            "required": [
              "fiscalYear",
              "periodStart",
              "periodEnd"
            ],
            "type": "object"
          },
          "settlements": {
            "properties": {
              "full": {
                "$ref": "#/components/schemas/ApportionmentSettlement"
              },
              "individual": {
                "$ref": "#/components/schemas/ApportionmentSettlement"
              },
              "proportional": {
                "$ref": "#/components/schemas/ApportionmentSettlement"
              }
            },
            "required": [
              "full",
              "individual",
              "proportional"
            ],
            "type": "object"
          },
          "summary": {
            "$ref": "#/components/schemas/ApportionmentSummary"
          }
        },
        "required": [
          "period",
          "isFiled",
          "filedMethodConflict",
          "methodEditable",
          "summary",
          "election",
          "lock",
          "settlements",
          "lines",
          "overriddenLines",
          "adjustmentAssets"
        ],
        "type": "object"
      },
      "ApportionmentOverviewResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/ApportionmentOverview"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "ApportionmentRateColumns": {
        "description": "One 付表2-3 row: A = 6.24%適用分, B = 7.8%適用分, C = A + B (national tax, yen).",
        "properties": {
          "reduced": {
            "example": 0,
            "type": "integer"
          },
          "standard": {
            "example": 873486,
            "type": "integer"
          },
          "total": {
            "example": 873486,
            "type": "integer"
          }
        },
        "required": [
          "reduced",
          "standard",
          "total"
        ],
        "type": "object"
      },
      "ApportionmentReviewLine": {
        "properties": {
          "accountCode": {
            "nullable": true,
            "type": "string"
          },
          "accountName": {
            "nullable": true,
            "type": "string"
          },
          "amountIncTax": {
            "type": "integer"
          },
          "creditFraction": {
            "type": "number"
          },
          "description": {
            "nullable": true,
            "type": "string"
          },
          "entryNumber": {
            "nullable": true,
            "type": "string"
          },
          "isAssetLine": {
            "type": "boolean"
          },
          "journalEntryId": {
            "type": "string"
          },
          "lineId": {
            "format": "uuid",
            "type": "string"
          },
          "nationalTax": {
            "description": "National tax this line contributes to ⑰",
            "type": "integer"
          },
          "purchaseDate": {
            "example": 20260706,
            "type": "integer"
          },
          "reasonJa": {
            "type": "string"
          },
          "residentialRentalEligible": {
            "description": "A 建物 (附属設備を含む) acquired at 税抜 ¥1,000万 or more — may be marked 居住用賃貸建物 (消法30条10項)",
            "type": "boolean"
          },
          "taxRate": {
            "enum": [
              "10%",
              "8%"
            ],
            "type": "string"
          },
          "useCategory": {
            "enum": [
              "taxable_only",
              "exempt_only",
              "common"
            ],
            "type": "string"
          },
          "useCategorySource": {
            "enum": [
              "manual",
              "account_default",
              "fallback"
            ],
            "type": "string"
          }
        },
        "required": [
          "lineId",
          "amountIncTax",
          "nationalTax",
          "useCategory",
          "useCategorySource",
          "reasonJa"
        ],
        "type": "object"
      },
      "ApportionmentSettlement": {
        "description": "The return bottom line under one method — 国税 refund exact to the yen (国税通則法120条), payable floored to ¥100 (消法45条), 地方 = 22/78.",
        "properties": {
          "isRefund": {
            "type": "boolean"
          },
          "outputNational": {
            "type": "integer"
          },
          "payableLocal": {
            "type": "integer"
          },
          "payableNational": {
            "type": "integer"
          },
          "refundLocal": {
            "type": "integer"
          },
          "refundNational": {
            "type": "integer"
          },
          "signedTotal": {
            "description": "Negative = 還付, positive = 納付",
            "type": "integer"
          }
        },
        "required": [
          "outputNational",
          "isRefund",
          "refundNational",
          "refundLocal",
          "payableNational",
          "payableLocal",
          "signedTotal"
        ],
        "type": "object"
      },
      "ApportionmentSummary": {
        "description": "課税売上割合 (付表2-3 ①〜⑧) and the 控除対象仕入税額 under 全額控除 (⑰/⑱), 個別対応方式 (⑲⑳㉑) and 一括比例配分方式 (㉒), with the method the period actually claims (`applied`). Computed once by the engine; the compare headline, the drill and the XTX read the same object.",
        "properties": {
          "annualizedTaxableSales": {
            "type": "integer"
          },
          "applied": {
            "$ref": "#/components/schemas/ApportionmentRateColumns"
          },
          "appliedMethod": {
            "enum": [
              "full",
              "individual",
              "proportional"
            ],
            "type": "string"
          },
          "classification": {
            "properties": {
              "autoCount": {
                "type": "integer"
              },
              "lineCount": {
                "type": "integer"
              },
              "manualCount": {
                "type": "integer"
              },
              "unclassifiedCount": {
                "description": "Fallback-only lines; they block 個別対応方式 XTX",
                "type": "integer"
              }
            },
            "required": [
              "lineCount",
              "manualCount",
              "autoCount",
              "unclassifiedCount"
            ],
            "type": "object"
          },
          "common": {
            "$ref": "#/components/schemas/ApportionmentRateColumns"
          },
          "electedMethod": {
            "enum": [
              "individual",
              "proportional",
              null
            ],
            "nullable": true,
            "type": "string"
          },
          "exemptOnly": {
            "$ref": "#/components/schemas/ApportionmentRateColumns"
          },
          "exemptSalesOnForm": {
            "description": "⑥ 非課税売上額",
            "type": "integer"
          },
          "exportSales": {
            "description": "② 免税売上額",
            "type": "integer"
          },
          "formPercent": {
            "description": "⑧ as written to DTD00000",
            "example": "0.00",
            "type": "string"
          },
          "full": {
            "$ref": "#/components/schemas/ApportionmentRateColumns"
          },
          "individual": {
            "$ref": "#/components/schemas/ApportionmentRateColumns"
          },
          "methodSource": {
            "enum": [
              "not_required",
              "elected",
              "default_individual",
              "as_filed"
            ],
            "type": "string"
          },
          "nonTaxableExportSales": {
            "description": "③ 非課税資産の輸出等",
            "type": "integer"
          },
          "proportional": {
            "$ref": "#/components/schemas/ApportionmentRateColumns"
          },
          "ratioDenominator": {
            "description": "⑦ 資産の譲渡等の対価の額",
            "type": "integer"
          },
          "ratioNumerator": {
            "description": "④ 課税資産の譲渡等の対価の額",
            "type": "integer"
          },
          "reason": {
            "enum": [
              "ratio_below_95",
              "sales_over_500m",
              null
            ],
            "nullable": true,
            "type": "string"
          },
          "requiresApportionment": {
            "description": "ratio < 95% or annualized 課税売上高 > ¥5億",
            "type": "boolean"
          },
          "taxableOnly": {
            "$ref": "#/components/schemas/ApportionmentRateColumns"
          },
          "taxableSalesExclTax": {
            "description": "① 課税売上額（税抜き）",
            "type": "integer"
          },
          "taxableSalesRatio": {
            "description": "Exact ④/⑦",
            "type": "number"
          },
          "taxableSalesRatioPct": {
            "description": "⑧ truncated to 2dp",
            "type": "number"
          },
          "warnings": {
            "items": {
              "type": "string"
            },
            "type": "array"
          }
        },
        "required": [
          "requiresApportionment",
          "ratioNumerator",
          "ratioDenominator",
          "formPercent",
          "appliedMethod",
          "methodSource",
          "full",
          "individual",
          "proportional",
          "applied",
          "classification",
          "warnings"
        ],
        "type": "object"
      },
      "AssetClassification": {
        "description": "Japanese tax law asset classification",
        "enum": [
          1,
          2,
          3,
          4,
          5,
          6,
          7,
          8,
          9
        ],
        "example": 6,
        "type": "integer",
        "x-enum-descriptions": [
          "建物 (Buildings)",
          "建物附属設備 (Building Fixtures)",
          "構築物 (Structures)",
          "機械装置 (Machinery and Equipment)",
          "車両運搬具 (Vehicles and Transportation Equipment)",
          "工具器具備品 (Tools, Equipment and Fixtures)",
          "土地 (Land)",
          "ソフトウェア (Software)",
          "その他 (Other Assets)"
        ],
        "x-enum-varnames": [
          "BUILDING",
          "BUILDING_FIXTURES",
          "STRUCTURES",
          "MACHINERY",
          "VEHICLES",
          "TOOLS_AND_EQUIPMENT",
          "LAND",
          "SOFTWARE",
          "OTHER"
        ]
      },
      "AuditActionType": {
        "description": "Audit action type for compliance trail",
        "enum": [
          "create",
          "update",
          "delete",
          "view",
          "download",
          "verify",
          "timestamp"
        ],
        "example": "create",
        "type": "string"
      },
      "AuditLogEntry": {
        "properties": {
          "actionDetails": {
            "description": "Detailed information about the action",
            "example": {
              "message": "タイムスタンプ付与",
              "token": "ts_abc123"
            },
            "type": "object"
          },
          "actionType": {
            "$ref": "#/components/schemas/AuditActionType"
          },
          "documentId": {
            "description": "Related document ID",
            "format": "uuid",
            "type": "string"
          },
          "id": {
            "description": "Audit log entry unique identifier",
            "format": "uuid",
            "type": "string"
          },
          "ipAddress": {
            "description": "IP address of the user",
            "example": "192.168.1.100",
            "nullable": true,
            "type": "string"
          },
          "newData": {
            "description": "New data state (for updates)",
            "nullable": true,
            "type": "object"
          },
          "previousData": {
            "description": "Previous data state (for updates)",
            "nullable": true,
            "type": "object"
          },
          "timestamp": {
            "description": "Action timestamp",
            "example": "2024-03-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "userAgent": {
            "description": "User agent string",
            "nullable": true,
            "type": "string"
          },
          "userId": {
            "description": "User who performed the action",
            "format": "uuid",
            "type": "string"
          }
        },
        "required": [
          "id",
          "documentId",
          "userId",
          "actionType",
          "actionDetails",
          "timestamp"
        ],
        "type": "object"
      },
      "AuditTrailResponse": {
        "properties": {
          "data": {
            "properties": {
              "auditLogs": {
                "items": {
                  "$ref": "#/components/schemas/AuditLogEntry"
                },
                "type": "array"
              },
              "documentId": {
                "example": "123e4567-e89b-12d3-a456-426614174000",
                "format": "uuid",
                "type": "string"
              }
            },
            "type": "object"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "AuditorViewFiscalYearQuery": {
        "properties": {
          "fiscal_year": {
            "example": 2025,
            "maximum": 2100,
            "minimum": 2000,
            "type": "integer"
          }
        },
        "type": "object"
      },
      "AuthErrorCode": {
        "description": "Authentication error codes for consistent error handling:\n- **NO_TOKEN**: No Authorization header provided\n- **INVALID_TOKEN_FORMAT**: JWT structure is malformed (not 3 parts)\n- **TOKEN_EXPIRED**: Access token has expired\n- **TOKEN_INVALID**: Supabase rejected the token\n- **REFRESH_FAILED**: Refresh token is invalid or expired\n- **INVALID_SESSION**: Session data is missing or corrupted\n- **AUTH_ERROR**: General authentication error\n- **USER_NOT_FOUND**: User doesn't exist in the system\n- **MISSING_SUB_CLAIM**: Token is missing 'sub' claim (likely an API key instead of user token)",
        "enum": [
          "NO_TOKEN",
          "INVALID_TOKEN_FORMAT",
          "TOKEN_EXPIRED",
          "TOKEN_INVALID",
          "REFRESH_FAILED",
          "INVALID_SESSION",
          "AUTH_ERROR",
          "USER_NOT_FOUND",
          "MISSING_SUB_CLAIM"
        ],
        "type": "string"
      },
      "AuthErrorResponse": {
        "properties": {
          "code": {
            "$ref": "#/components/schemas/AuthErrorCode"
          },
          "details": {
            "description": "Additional error details (development mode only)",
            "properties": {
              "hint": {
                "example": "Include Authorization header with Bearer token",
                "type": "string"
              },
              "supabaseError": {
                "example": "JWT expired",
                "type": "string"
              }
            },
            "type": "object"
          },
          "error": {
            "description": "Human-readable error message",
            "example": "No authentication token provided",
            "type": "string"
          }
        },
        "required": [
          "error",
          "code"
        ],
        "type": "object"
      },
      "AuthTokenResponse": {
        "description": "The refresh token is NOT included in this response. It is stored as an httpOnly cookie (Set-Cookie header) that the browser sends automatically on subsequent requests. This prevents XSS from accessing the refresh token.",
        "properties": {
          "data": {
            "properties": {
              "accessToken": {
                "description": "JWT access token for API authentication. Store in memory only (not localStorage).",
                "example": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
                "type": "string"
              },
              "expiresIn": {
                "description": "Token expiration time in seconds",
                "example": 3600,
                "type": "number"
              },
              "isNewUser": {
                "description": "True when this callback created the profile (first login). The frontend routes a first login to /start (GTM Phase 2). Absent on refresh.",
                "example": false,
                "type": "boolean"
              }
            },
            "required": [
              "accessToken",
              "expiresIn"
            ],
            "type": "object"
          },
          "message": {
            "example": "Authentication successful",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "AutoGenerateFiscalYearRequest": {
        "properties": {
          "company_id": {
            "description": "Company ID (optional)",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "fiscal_year_end": {
            "description": "Fiscal year end date in YYYYMMDD format",
            "example": 20250331,
            "type": "integer"
          },
          "fiscal_year_start": {
            "description": "Fiscal year start date in YYYYMMDD format",
            "example": 20240401,
            "type": "integer"
          },
          "generate_monthly": {
            "default": true,
            "description": "Generate monthly periods instead of quarterly",
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "fiscal_year_start",
          "fiscal_year_end"
        ],
        "type": "object"
      },
      "AutoSaveDocumentResponse": {
        "properties": {
          "data": {
            "description": "Auto-save document or null if none exists",
            "oneOf": [
              {
                "$ref": "#/components/schemas/Document"
              },
              {
                "type": "null"
              }
            ]
          },
          "message": {
            "example": "Auto-save document retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "AvailableDocument": {
        "properties": {
          "createdAt": {
            "description": "Document creation timestamp",
            "example": "2024-02-01T09:00:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "currency": {
            "description": "Currency code",
            "example": "JPY",
            "type": "string"
          },
          "id": {
            "description": "Document identifier",
            "example": "789e0123-e45b-67c8-d901-234567890123",
            "format": "uuid",
            "type": "string"
          },
          "name": {
            "description": "Document name",
            "example": "2024年2月経費精算書 - 営業部",
            "type": "string"
          },
          "status": {
            "description": "Document status",
            "enum": [
              "draft",
              "published",
              "archived"
            ],
            "example": "draft",
            "type": "string"
          },
          "totalAmount": {
            "description": "Document total amount",
            "example": 32000,
            "type": "number"
          },
          "type": {
            "description": "Document type",
            "example": "claims",
            "type": "string"
          }
        },
        "required": [
          "id",
          "name",
          "type",
          "status",
          "totalAmount",
          "currency",
          "createdAt"
        ],
        "type": "object"
      },
      "AvailableDocumentsResponse": {
        "properties": {
          "data": {
            "properties": {
              "availableDocuments": {
                "example": 5,
                "type": "integer"
              },
              "documents": {
                "items": {
                  "$ref": "#/components/schemas/AvailableDocument"
                },
                "type": "array"
              },
              "linkType": {
                "example": "travel_to_claims",
                "type": "string"
              },
              "targetDocumentType": {
                "example": "claims",
                "type": "string"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Available documents retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "AwardXPRequest": {
        "properties": {
          "amount": {
            "description": "Override default XP amount",
            "maximum": 10000,
            "minimum": 0,
            "type": "integer"
          },
          "event_type": {
            "description": "Type of XP event",
            "enum": [
              "login",
              "consecutive_login",
              "document_create",
              "document_upload",
              "document_scan",
              "document_approve",
              "transaction_categorize",
              "transaction_reconcile",
              "transaction_bulk_process",
              "report_generate",
              "report_view",
              "dashboard_view",
              "ai_suggestion_accept",
              "ai_coach_question",
              "settings_update",
              "bank_connect",
              "goal_complete",
              "achievement_unlock"
            ],
            "type": "string"
          },
          "metadata": {
            "description": "Additional metadata",
            "type": "object"
          },
          "source_entity_id": {
            "description": "Entity ID",
            "format": "uuid",
            "type": "string"
          },
          "source_entity_type": {
            "description": "Entity type (document, transaction, etc.)",
            "maxLength": 50,
            "type": "string"
          }
        },
        "required": [
          "event_type"
        ],
        "type": "object"
      },
      "AwardXPResponse": {
        "properties": {
          "daily_limit_reached": {
            "example": false,
            "type": "boolean"
          },
          "leveled_up": {
            "example": false,
            "type": "boolean"
          },
          "new_level": {
            "nullable": true,
            "type": "integer"
          },
          "new_total_xp": {
            "example": 770,
            "type": "integer"
          },
          "streak_multiplier": {
            "nullable": true,
            "type": "number"
          },
          "xp_awarded": {
            "example": 20,
            "type": "integer"
          }
        },
        "type": "object"
      },
      "BSLineItem": {
        "properties": {
          "amount": {
            "description": "Current period amount in JPY",
            "example": 2500000,
            "format": "decimal",
            "type": "number"
          },
          "code": {
            "description": "Account code",
            "example": "1110",
            "type": "string"
          },
          "name": {
            "description": "Account name in English",
            "example": "Cash and Deposits",
            "type": "string"
          },
          "nameJa": {
            "description": "Account name in Japanese",
            "example": "現金及び預金",
            "type": "string"
          },
          "priorAmount": {
            "description": "Prior period amount in JPY",
            "example": 2200000,
            "format": "decimal",
            "nullable": true,
            "type": "number"
          }
        },
        "required": [
          "code",
          "name",
          "nameJa",
          "amount"
        ],
        "type": "object"
      },
      "BSSection": {
        "properties": {
          "items": {
            "description": "Line items in this section",
            "items": {
              "$ref": "#/components/schemas/BSLineItem"
            },
            "type": "array"
          },
          "priorTotal": {
            "description": "Prior period section total",
            "example": 3200000,
            "format": "decimal",
            "nullable": true,
            "type": "number"
          },
          "title": {
            "description": "Section title in English",
            "example": "Current Assets",
            "type": "string"
          },
          "titleJa": {
            "description": "Section title in Japanese",
            "example": "流動資産",
            "type": "string"
          },
          "total": {
            "description": "Section total amount in JPY",
            "example": 3500000,
            "format": "decimal",
            "type": "number"
          }
        },
        "required": [
          "title",
          "titleJa",
          "items",
          "total"
        ],
        "type": "object"
      },
      "BackfillDocumentLinksResponse": {
        "description": "Response from document-client backfill operation",
        "properties": {
          "data": {
            "properties": {
              "matchedDocuments": {
                "description": "Documents that matched a client by name",
                "example": 45,
                "type": "number"
              },
              "matches": {
                "description": "List of document-client matches",
                "items": {
                  "properties": {
                    "clientId": {
                      "format": "uuid",
                      "type": "string"
                    },
                    "clientName": {
                      "example": "ABC株式会社",
                      "type": "string"
                    },
                    "documentId": {
                      "format": "uuid",
                      "type": "string"
                    },
                    "documentName": {
                      "example": "見積書_ABC株式会社",
                      "type": "string"
                    },
                    "documentType": {
                      "example": "sales_quotation",
                      "type": "string"
                    },
                    "matchField": {
                      "enum": [
                        "clientInfo",
                        "buyerInfo",
                        "supplierInfo"
                      ],
                      "example": "clientInfo",
                      "type": "string"
                    }
                  },
                  "type": "object"
                },
                "type": "array"
              },
              "totalDocuments": {
                "description": "Total documents without client_id",
                "example": 150,
                "type": "number"
              },
              "updatedDocuments": {
                "description": "Documents actually updated (0 if dryRun)",
                "example": 0,
                "type": "number"
              }
            },
            "required": [
              "totalDocuments",
              "matchedDocuments",
              "updatedDocuments",
              "matches"
            ],
            "type": "object"
          },
          "message": {
            "example": "Dry run complete. Found 45 documents that can be linked to clients.",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "BackupEmailResponse": {
        "properties": {
          "data": {
            "properties": {
              "email": {
                "description": "Full backup email (only for owner)",
                "example": "backup@example.com",
                "nullable": true,
                "type": "string"
              },
              "emailMasked": {
                "description": "Masked email for display",
                "example": "ba***@example.com",
                "nullable": true,
                "type": "string"
              },
              "isVerified": {
                "description": "Whether email is verified",
                "type": "boolean"
              },
              "verifiedAt": {
                "format": "date-time",
                "nullable": true,
                "type": "string"
              }
            },
            "type": "object"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "type": "object"
      },
      "BalanceSheetStatement": {
        "properties": {
          "asOfDate": {
            "$ref": "#/components/schemas/DateFormat"
          },
          "assets": {
            "properties": {
              "current": {
                "$ref": "#/components/schemas/BSSection"
              },
              "deferred": {
                "$ref": "#/components/schemas/BSSection"
              },
              "fixed": {
                "properties": {
                  "intangible": {
                    "$ref": "#/components/schemas/BSSection"
                  },
                  "investments": {
                    "$ref": "#/components/schemas/BSSection"
                  },
                  "priorTotal": {
                    "format": "decimal",
                    "nullable": true,
                    "type": "number"
                  },
                  "tangible": {
                    "$ref": "#/components/schemas/BSSection"
                  },
                  "total": {
                    "format": "decimal",
                    "type": "number"
                  }
                },
                "type": "object"
              },
              "priorTotal": {
                "format": "decimal",
                "nullable": true,
                "type": "number"
              },
              "total": {
                "format": "decimal",
                "type": "number"
              }
            },
            "type": "object"
          },
          "equity": {
            "properties": {
              "capital": {
                "format": "decimal",
                "type": "number"
              },
              "capitalSurplus": {
                "format": "decimal",
                "type": "number"
              },
              "currentYearProfit": {
                "format": "decimal",
                "type": "number"
              },
              "priorTotal": {
                "format": "decimal",
                "nullable": true,
                "type": "number"
              },
              "retainedEarnings": {
                "format": "decimal",
                "type": "number"
              },
              "total": {
                "format": "decimal",
                "type": "number"
              }
            },
            "type": "object"
          },
          "fiscalYear": {
            "example": "2024年度",
            "type": "string"
          },
          "isBalanced": {
            "example": true,
            "type": "boolean"
          },
          "liabilities": {
            "properties": {
              "current": {
                "$ref": "#/components/schemas/BSSection"
              },
              "longTerm": {
                "$ref": "#/components/schemas/BSSection"
              },
              "priorTotal": {
                "format": "decimal",
                "nullable": true,
                "type": "number"
              },
              "total": {
                "format": "decimal",
                "type": "number"
              }
            },
            "type": "object"
          },
          "priorAsOfDate": {
            "$ref": "#/components/schemas/DateFormat"
          },
          "priorTotalLiabilitiesAndEquity": {
            "format": "decimal",
            "nullable": true,
            "type": "number"
          },
          "totalLiabilitiesAndEquity": {
            "format": "decimal",
            "type": "number"
          }
        },
        "required": [
          "asOfDate",
          "fiscalYear",
          "assets",
          "liabilities",
          "equity",
          "totalLiabilitiesAndEquity",
          "isBalanced"
        ],
        "type": "object"
      },
      "BankAccountInput": {
        "properties": {
          "code": {
            "description": "Bank account code",
            "example": "MAIN_001",
            "type": "string"
          },
          "name": {
            "description": "Bank account name",
            "example": "メイン普通預金",
            "type": "string"
          }
        },
        "required": [
          "code",
          "name"
        ],
        "type": "object"
      },
      "BankAccountSettings": {
        "properties": {
          "account_holder_name": {
            "description": "Account holder name",
            "example": "ヤマダ タロウ",
            "maxLength": 100,
            "type": "string"
          },
          "account_number": {
            "description": "Bank account number (7-8 digits)",
            "example": "1234567",
            "nullable": true,
            "pattern": "^\\d{7,8}$",
            "type": "string"
          },
          "account_type": {
            "description": "Japanese bank account type",
            "enum": [
              "普通",
              "当座",
              "貯蓄"
            ],
            "example": "普通",
            "nullable": true,
            "type": "string"
          },
          "bank_code": {
            "description": "Japanese bank code (4 digits)",
            "example": "0001",
            "nullable": true,
            "pattern": "^\\d{4}$",
            "type": "string"
          },
          "bank_name": {
            "description": "Bank name",
            "example": "みずほ銀行",
            "maxLength": 100,
            "type": "string"
          },
          "branch_code": {
            "description": "Bank branch code (3 digits)",
            "example": "001",
            "nullable": true,
            "pattern": "^\\d{3}$",
            "type": "string"
          },
          "branch_name": {
            "description": "Bank branch name",
            "example": "東京営業部",
            "maxLength": 50,
            "nullable": true,
            "type": "string"
          },
          "company_id": {
            "description": "Company identifier (optional)",
            "example": "123e4567-e89b-12d3-a456-426614174001",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "created_at": {
            "description": "Creation timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "id": {
            "description": "Unique settings identifier",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "updated_at": {
            "description": "Last update timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "user_id": {
            "description": "User identifier",
            "example": "550e8400-e29b-41d4-a716-446655440000",
            "format": "uuid",
            "type": "string"
          }
        },
        "required": [
          "id",
          "user_id",
          "bank_name",
          "account_holder_name",
          "created_at",
          "updated_at"
        ],
        "type": "object"
      },
      "BankAccountSettingsDeleteResponse": {
        "properties": {
          "data": {
            "type": "null"
          },
          "message": {
            "example": "Bank account settings deleted successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "BankAccountSettingsResponse": {
        "properties": {
          "data": {
            "oneOf": [
              {
                "$ref": "#/components/schemas/BankAccountSettings"
              },
              {
                "type": "null"
              }
            ]
          },
          "message": {
            "example": "Bank account settings retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "BankAccountSettingsUpdateResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/BankAccountSettings"
          },
          "message": {
            "example": "Bank account settings updated successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "BankAccountWithBalance": {
        "properties": {
          "account_holder_name": {
            "example": "ヤマダ タロウ",
            "maxLength": 100,
            "type": "string"
          },
          "account_number": {
            "example": "1234567",
            "nullable": true,
            "pattern": "^\\d{7,8}$",
            "type": "string"
          },
          "account_type": {
            "enum": [
              "普通",
              "当座",
              "貯蓄"
            ],
            "example": "普通",
            "nullable": true,
            "type": "string"
          },
          "bank_code": {
            "example": "0001",
            "nullable": true,
            "pattern": "^\\d{4}$",
            "type": "string"
          },
          "bank_name": {
            "example": "みずほ銀行",
            "maxLength": 100,
            "type": "string"
          },
          "branch_code": {
            "example": "001",
            "nullable": true,
            "pattern": "^\\d{3}$",
            "type": "string"
          },
          "branch_name": {
            "example": "東京営業部",
            "maxLength": 50,
            "nullable": true,
            "type": "string"
          },
          "company_id": {
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "connection_status": {
            "description": "Present when include_connection_status=true",
            "enum": [
              "connected",
              "disconnected"
            ],
            "nullable": true,
            "type": "string"
          },
          "created_at": {
            "format": "date-time",
            "type": "string"
          },
          "display_name": {
            "example": "事業用メイン口座",
            "maxLength": 100,
            "nullable": true,
            "type": "string"
          },
          "id": {
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "is_primary": {
            "description": "At most one primary account per user+company",
            "example": true,
            "type": "boolean"
          },
          "last_sync_at": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "last_transaction_date": {
            "format": "date",
            "nullable": true,
            "type": "string"
          },
          "latest_balance": {
            "description": "IntJPY. Present when include_latest_balance=true",
            "nullable": true,
            "type": "integer"
          },
          "loan_end_date": {
            "format": "date",
            "nullable": true,
            "type": "string"
          },
          "loan_interest_rate": {
            "example": 1.5,
            "nullable": true,
            "type": "number"
          },
          "loan_lender_name": {
            "maxLength": 100,
            "nullable": true,
            "type": "string"
          },
          "loan_original_amount": {
            "description": "IntJPY — no decimals",
            "minimum": 0,
            "nullable": true,
            "type": "integer"
          },
          "loan_start_date": {
            "format": "date",
            "nullable": true,
            "type": "string"
          },
          "loan_type": {
            "description": "director_to_company / company_to_director only valid when entity_type = 法人 (corporation)",
            "enum": [
              "bank",
              "director_to_company",
              "company_to_director",
              "policy",
              "other"
            ],
            "nullable": true,
            "type": "string"
          },
          "purpose": {
            "enum": [
              "business",
              "personal",
              "reimbursement",
              "loan",
              "savings",
              "tax_payment",
              "payroll",
              "deposit",
              "other"
            ],
            "example": "business",
            "type": "string"
          },
          "sort_order": {
            "description": "Display ordering — lower first",
            "example": 0,
            "minimum": 0,
            "type": "integer"
          },
          "transaction_count": {
            "minimum": 0,
            "nullable": true,
            "type": "integer"
          },
          "updated_at": {
            "format": "date-time",
            "type": "string"
          },
          "user_id": {
            "example": "550e8400-e29b-41d4-a716-446655440000",
            "format": "uuid",
            "type": "string"
          }
        },
        "required": [
          "id",
          "user_id",
          "bank_name",
          "account_holder_name",
          "purpose",
          "created_at",
          "updated_at"
        ],
        "type": "object"
      },
      "BankConnection": {
        "properties": {
          "connectionStatus": {
            "enum": [
              "pending",
              "active",
              "expired",
              "revoked",
              "error"
            ],
            "type": "string"
          },
          "createdAt": {
            "format": "date-time",
            "type": "string"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "lastSyncAt": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "lastSyncError": {
            "nullable": true,
            "type": "string"
          },
          "lastSyncStatus": {
            "enum": [
              "success",
              "partial",
              "error"
            ],
            "nullable": true,
            "type": "string"
          },
          "metadata": {
            "type": "object"
          },
          "provider": {
            "example": "gmo_aozora",
            "type": "string"
          },
          "providerAccountId": {
            "nullable": true,
            "type": "string"
          },
          "providerLabel": {
            "example": "GMOあおぞらネット銀行 - 普通 ****1234",
            "type": "string"
          },
          "updatedAt": {
            "format": "date-time",
            "type": "string"
          },
          "webhookEnabled": {
            "type": "boolean"
          }
        },
        "type": "object"
      },
      "BankInfo": {
        "properties": {
          "account_holder": {
            "description": "Account holder name (口座名義)",
            "example": "株式会社サンプル",
            "type": "string"
          },
          "account_number": {
            "description": "Account number (口座番号)",
            "example": "1234567",
            "type": "string"
          },
          "account_type": {
            "$ref": "#/components/schemas/AccountType"
          },
          "bank_name": {
            "description": "Bank name (銀行名)",
            "example": "三菱UFJ銀行",
            "type": "string"
          },
          "branch_name": {
            "description": "Branch name (支店名)",
            "example": "新宿支店",
            "type": "string"
          }
        },
        "required": [
          "bank_name",
          "branch_name",
          "account_type",
          "account_number",
          "account_holder"
        ],
        "type": "object"
      },
      "BankProviderInfo": {
        "properties": {
          "displayName": {
            "example": "GMOあおぞらネット銀行",
            "type": "string"
          },
          "displayNameEn": {
            "example": "GMO Aozora Net Bank",
            "type": "string"
          },
          "isAvailable": {
            "example": true,
            "type": "boolean"
          },
          "logoUrl": {
            "nullable": true,
            "type": "string"
          },
          "providerId": {
            "example": "gmo_aozora",
            "type": "string"
          },
          "supportedFeatures": {
            "example": [
              "accounts",
              "balances",
              "transactions",
              "deposits",
              "webhooks"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          }
        },
        "type": "object"
      },
      "BankReconciliationReport": {
        "properties": {
          "data": {
            "properties": {
              "bankAmountMismatch": {
                "items": {
                  "type": "object"
                },
                "type": "array"
              },
              "bankRows": {
                "type": "integer"
              },
              "bankWithDeadJournal": {
                "items": {
                  "type": "object"
                },
                "type": "array"
              },
              "bankWithoutJournal": {
                "items": {
                  "type": "object"
                },
                "type": "array"
              },
              "deposits": {
                "type": "number"
              },
              "journalWithoutBank": {
                "items": {
                  "type": "object"
                },
                "type": "array"
              },
              "matched": {
                "properties": {
                  "amount": {
                    "type": "number"
                  },
                  "count": {
                    "type": "integer"
                  }
                },
                "type": "object"
              },
              "nonCashEntries": {
                "items": {
                  "type": "object"
                },
                "type": "array"
              },
              "periodEnd": {
                "type": "integer"
              },
              "periodStart": {
                "type": "integer"
              },
              "withdrawals": {
                "type": "number"
              }
            },
            "required": [
              "periodStart",
              "periodEnd",
              "bankRows",
              "matched",
              "bankWithoutJournal",
              "journalWithoutBank",
              "nonCashEntries"
            ],
            "type": "object"
          },
          "success": {
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "BankStatement": {
        "properties": {
          "balance": {
            "description": "Account balance after transaction in JPY",
            "example": 1250000,
            "format": "decimal",
            "type": "number"
          },
          "bankAccountId": {
            "description": "Associated bank account ID",
            "example": "789e0123-e45b-67c8-d901-234567890123",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "category": {
            "$ref": "#/components/schemas/TransactionCategory"
          },
          "counterpartyAccount": {
            "description": "Counterparty bank account number (Japanese format)",
            "example": "1234567",
            "nullable": true,
            "pattern": "^[0-9]{1,8}$",
            "type": "string"
          },
          "counterpartyBankCode": {
            "description": "Counterparty bank code (4 digits)",
            "example": "0001",
            "nullable": true,
            "pattern": "^[0-9]{4}$",
            "type": "string"
          },
          "counterpartyBranchCode": {
            "description": "Counterparty branch code (3 digits)",
            "example": "123",
            "nullable": true,
            "pattern": "^[0-9]{3}$",
            "type": "string"
          },
          "counterpartyName": {
            "description": "Counterparty name (Japanese)",
            "example": "タナカ タロウ",
            "maxLength": 255,
            "nullable": true,
            "type": "string"
          },
          "createdAt": {
            "description": "Statement creation timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "depositAmount": {
            "description": "Deposit amount in JPY (positive value)",
            "example": 300000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "description": {
            "description": "Transaction description or memo",
            "example": "振込 タナカ タロウ",
            "maxLength": 255,
            "type": "string"
          },
          "duplicateOfId": {
            "description": "Original statement ID if this is a duplicate",
            "example": null,
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "id": {
            "description": "Bank statement unique identifier",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "importBatchId": {
            "description": "Import batch ID for tracking bulk imports",
            "example": "987e6543-f21a-43b5-c678-109876543210",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "importHash": {
            "description": "Hash for duplicate detection",
            "example": "a1b2c3d4e5f6",
            "nullable": true,
            "type": "string"
          },
          "isDuplicate": {
            "description": "Whether this statement is marked as duplicate",
            "example": false,
            "type": "boolean"
          },
          "journalEntryId": {
            "description": "Associated journal entry ID for accounting integration",
            "example": "456e7890-f12a-34b5-c678-901234567890",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "linkedCounts": {
            "description": "Inline linked counts (only present when include_linked_counts=true, v4.27+)",
            "nullable": true,
            "properties": {
              "documentCount": {
                "description": "Number of documents linked to this transaction",
                "example": 2,
                "minimum": 0,
                "type": "integer"
              },
              "hasJournal": {
                "description": "Whether a journal entry is linked",
                "example": true,
                "type": "boolean"
              },
              "journalCreditAccount": {
                "description": "Credit account name (only when hasJournal is true)",
                "example": "売上高",
                "type": "string"
              },
              "journalCreditCode": {
                "description": "Credit account code (only when hasJournal is true)",
                "example": "4001",
                "type": "string"
              },
              "journalDebitAccount": {
                "description": "Debit account name (only when hasJournal is true)",
                "example": "普通預金",
                "type": "string"
              },
              "journalDebitCode": {
                "description": "Debit account code (only when hasJournal is true)",
                "example": "1111",
                "type": "string"
              },
              "processingStatus": {
                "description": "Derived processing status",
                "enum": [
                  "unprocessed",
                  "journal_only",
                  "doc_only",
                  "complete"
                ],
                "example": "complete",
                "type": "string"
              }
            },
            "type": "object"
          },
          "memo": {
            "description": "Additional memo or notes",
            "example": "Monthly salary payment",
            "maxLength": 500,
            "nullable": true,
            "type": "string"
          },
          "transactionDate": {
            "description": "Transaction date in YYYYMMDD format",
            "example": 20240115,
            "maximum": 99991231,
            "minimum": 19700101,
            "type": "integer"
          },
          "userId": {
            "description": "User who owns this bank statement",
            "example": "abc12345-def6-7890-ghij-klmnopqrstuv",
            "format": "uuid",
            "type": "string"
          },
          "withdrawalAmount": {
            "description": "Withdrawal amount in JPY (positive value)",
            "example": 0,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          }
        },
        "required": [
          "id",
          "userId",
          "transactionDate",
          "description",
          "balance",
          "depositAmount",
          "withdrawalAmount",
          "category",
          "isDuplicate",
          "createdAt"
        ],
        "type": "object"
      },
      "BankStatementAuditLog": {
        "allOf": [
          {
            "$ref": "#/components/schemas/AuditLogEntry"
          },
          {
            "properties": {
              "bank_statement_id": {
                "description": "Referenced bank statement ID",
                "format": "uuid",
                "type": "string"
              }
            },
            "required": [
              "bank_statement_id"
            ],
            "type": "object"
          }
        ],
        "description": "Audit log for bank_statements table. Added in v5.13. Triggers: INSERT, UPDATE, DELETE."
      },
      "BankStatementBatchLinkedCountsRequest": {
        "additionalProperties": false,
        "properties": {
          "ids": {
            "items": {
              "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i",
              "type": "string"
            },
            "type": "array"
          }
        },
        "required": [
          "ids"
        ],
        "type": "object"
      },
      "BankStatementBulkAssignAccountRequest": {
        "additionalProperties": false,
        "properties": {
          "bank_account_id": {
            "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i",
            "type": "string"
          },
          "transaction_ids": {
            "items": {
              "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i",
              "type": "string"
            },
            "maxItems": 500,
            "type": "array"
          }
        },
        "required": [
          "transaction_ids",
          "bank_account_id"
        ],
        "type": "object"
      },
      "BankStatementImportFromTextRequest": {
        "additionalProperties": false,
        "properties": {
          "provider": {
            "enum": [
              "openai",
              "claude",
              "gemini",
              "together"
            ],
            "type": "string"
          },
          "text": {
            "maxLength": 500000,
            "minLength": 1,
            "type": "string"
          }
        },
        "required": [
          "text"
        ],
        "type": "object"
      },
      "BankStatementListResponse": {
        "properties": {
          "_meta": {
            "description": "Additional metadata (only present when results are truncated)",
            "nullable": true,
            "properties": {
              "message": {
                "description": "Human-readable message about truncation",
                "example": "Results truncated to 50000 records. Use date filters to narrow your query.",
                "type": "string"
              },
              "safety_limit": {
                "description": "Maximum records allowed per request",
                "example": 50000,
                "type": "integer"
              },
              "truncated": {
                "description": "Whether results were truncated due to safety limit",
                "example": true,
                "type": "boolean"
              }
            },
            "type": "object"
          },
          "data": {
            "items": {
              "$ref": "#/components/schemas/BankStatement"
            },
            "type": "array"
          },
          "isEmpty": {
            "description": "Present (true) only when the result set is empty",
            "example": false,
            "type": "boolean"
          },
          "message": {
            "example": "銀行取引を取得しました",
            "type": "string"
          },
          "pagination": {
            "$ref": "#/components/schemas/Pagination"
          },
          "periodTotals": {
            "description": "入金 / 出金 for the WHOLE slice (BL-1164) — the same bank_account_id / source / period filters as\nthe list, independent of paging, so the period strip and the month subtotals need not wait for every page.\n\nAmounts count each movement once: `is_duplicate` rows are listed but left out of every total, so the totals can\nbe lower than the sum of the rows on screen. `months[].rowCount` counts the rows the list shows under that month,\nduplicates included. Like `unjournalizedCount`, it ignores `include_deleted` and `for_reconciliation` and\nalways describes live rows. Integer JPY; months newest first.",
            "properties": {
              "depositTotal": {
                "example": 50338934,
                "type": "integer"
              },
              "months": {
                "items": {
                  "properties": {
                    "depositTotal": {
                      "example": 4200000,
                      "type": "integer"
                    },
                    "month": {
                      "example": "2026-09",
                      "pattern": "^\\d{4}-\\d{2}$",
                      "type": "string"
                    },
                    "rowCount": {
                      "example": 31,
                      "type": "integer"
                    },
                    "withdrawalTotal": {
                      "example": 3815500,
                      "type": "integer"
                    }
                  },
                  "required": [
                    "month",
                    "rowCount",
                    "depositTotal",
                    "withdrawalTotal"
                  ],
                  "type": "object"
                },
                "type": "array"
              },
              "movementCount": {
                "description": "Rows in the totals (duplicates excluded)",
                "example": 285,
                "type": "integer"
              },
              "withdrawalTotal": {
                "example": 48120400,
                "type": "integer"
              }
            },
            "required": [
              "depositTotal",
              "withdrawalTotal",
              "movementCount",
              "months"
            ],
            "type": "object"
          },
          "requestId": {
            "description": "Trace ID for support tickets (present when available)",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          },
          "unjournalizedCount": {
            "description": "未仕訳件数 (v5.20+, BL-481) — how many LIVE transactions under the SAME\nbank_account_id / source / period filters still have no journal entry (is_duplicate = false,\ndeleted_at IS NULL, journal_entry_id IS NULL). Always present, independent of paging, so the 一括仕訳 badge\nnever has to drain extra pages to count rows.\n\nIt deliberately ignores `include_deleted` and `for_reconciliation`: 未仕訳 always counts live rows that\nstill need a journal entry, so with either flag on the count can differ from the rows on screen. Fetch the\nmatching ids from `GET /api/bank-statements/unjournalized-ids`.",
            "example": 12,
            "type": "integer"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "BankStatementOverview": {
        "additionalProperties": false,
        "properties": {
          "accounts": {
            "description": "All bank accounts, primary first, then sortOrder",
            "items": {
              "additionalProperties": false,
              "properties": {
                "accountNumber": {
                  "example": "1234567",
                  "nullable": true,
                  "type": "string"
                },
                "accountType": {
                  "example": "普通",
                  "nullable": true,
                  "type": "string"
                },
                "bankName": {
                  "example": "GMOあおぞらネット銀行",
                  "type": "string"
                },
                "branchName": {
                  "example": "法人営業部",
                  "nullable": true,
                  "type": "string"
                },
                "connectionStatus": {
                  "description": "connected when an active bank connection syncs THIS account; otherwise null",
                  "enum": [
                    "connected",
                    null
                  ],
                  "example": "connected",
                  "nullable": true,
                  "type": "string"
                },
                "displayName": {
                  "example": "メイン事業用口座",
                  "nullable": true,
                  "type": "string"
                },
                "id": {
                  "format": "uuid",
                  "type": "string"
                },
                "importSources": {
                  "additionalProperties": false,
                  "description": "Row counts per import method for this account (`paste` = the コピペ import)",
                  "properties": {
                    "csvImport": {
                      "example": 6,
                      "type": "integer"
                    },
                    "manual": {
                      "example": 150,
                      "type": "integer"
                    },
                    "paste": {
                      "example": 0,
                      "type": "integer"
                    }
                  },
                  "required": [
                    "manual",
                    "csvImport",
                    "paste"
                  ],
                  "type": "object"
                },
                "isPrimary": {
                  "example": true,
                  "type": "boolean"
                },
                "lastSyncAt": {
                  "format": "date-time",
                  "nullable": true,
                  "type": "string"
                },
                "lastTransactionDate": {
                  "description": "Newest transaction_date (YYYYMMDD) on this account",
                  "example": 20260212,
                  "nullable": true,
                  "type": "integer"
                },
                "latestBalance": {
                  "description": "Running balance of the newest row on the newest transaction date; null with no rows",
                  "example": 1250000,
                  "nullable": true,
                  "type": "number"
                },
                "latestSource": {
                  "description": "How the newest statement row for this account was entered (bank_statements.source of the latest row; `api_gmo_aozora` = synced via the GMO Aozora API)",
                  "enum": [
                    "manual",
                    "csv_import",
                    "api_gmo_aozora",
                    "paste",
                    null
                  ],
                  "example": "manual",
                  "nullable": true,
                  "type": "string"
                },
                "purpose": {
                  "enum": [
                    "business",
                    "personal",
                    "reimbursement",
                    "loan",
                    "savings",
                    "tax_payment",
                    "payroll",
                    "deposit",
                    "other",
                    null
                  ],
                  "example": "business",
                  "nullable": true,
                  "type": "string"
                },
                "sortOrder": {
                  "example": 0,
                  "type": "integer"
                },
                "transactionCount": {
                  "example": 156,
                  "type": "integer"
                }
              },
              "required": [
                "id",
                "bankName",
                "isPrimary",
                "sortOrder",
                "transactionCount",
                "importSources"
              ],
              "type": "object"
            },
            "type": "array"
          },
          "summary": {
            "additionalProperties": false,
            "properties": {
              "dateRange": {
                "additionalProperties": false,
                "properties": {
                  "earliest": {
                    "example": 20240101,
                    "nullable": true,
                    "type": "integer"
                  },
                  "latest": {
                    "example": 20260212,
                    "nullable": true,
                    "type": "integer"
                  }
                },
                "required": [
                  "earliest",
                  "latest"
                ],
                "type": "object"
              },
              "totalBalance": {
                "example": 3500000,
                "nullable": true,
                "type": "number"
              },
              "totalTransactions": {
                "example": 718,
                "type": "integer"
              },
              "unassignedCount": {
                "description": "Transactions with bank_account_id IS NULL",
                "example": 45,
                "type": "integer"
              },
              "unreconciledCount": {
                "description": "Transactions with reconciliation_status pending or null",
                "example": 120,
                "type": "integer"
              }
            },
            "required": [
              "totalTransactions",
              "totalBalance",
              "unassignedCount",
              "unreconciledCount",
              "dateRange"
            ],
            "type": "object"
          },
          "syncStatus": {
            "additionalProperties": false,
            "properties": {
              "connections": {
                "items": {
                  "additionalProperties": false,
                  "properties": {
                    "id": {
                      "format": "uuid",
                      "type": "string"
                    },
                    "lastSyncAt": {
                      "format": "date-time",
                      "nullable": true,
                      "type": "string"
                    },
                    "lastSyncStatus": {
                      "example": "success",
                      "nullable": true,
                      "type": "string"
                    },
                    "provider": {
                      "example": "gmo_aozora",
                      "type": "string"
                    },
                    "status": {
                      "description": "connection_status, or unknown when unset",
                      "example": "active",
                      "type": "string"
                    }
                  },
                  "required": [
                    "id",
                    "provider",
                    "status"
                  ],
                  "type": "object"
                },
                "type": "array"
              }
            },
            "required": [
              "connections"
            ],
            "type": "object"
          }
        },
        "required": [
          "accounts",
          "summary",
          "syncStatus"
        ],
        "type": "object"
      },
      "BankStatementResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/BankStatement"
          },
          "message": {
            "example": "Bank statement created successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "BankStatementTransactionLinkParams": {
        "additionalProperties": false,
        "properties": {
          "id": {
            "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i",
            "type": "string"
          },
          "target_id": {
            "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i",
            "type": "string"
          }
        },
        "required": [
          "id",
          "target_id"
        ],
        "type": "object"
      },
      "BankStatementZenginCsvImportRequest": {
        "additionalProperties": false,
        "properties": {
          "bank_account_id": {
            "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i",
            "type": "string"
          },
          "commit": {
            "default": false,
            "type": "boolean"
          },
          "file_base64": {
            "maxLength": 7000000,
            "minLength": 1,
            "pattern": "^[A-Za-z0-9+/]+={0,2}$",
            "type": "string"
          },
          "file_name": {
            "maxLength": 255,
            "type": "string"
          },
          "inquiry_numbers": {
            "items": {
              "maxLength": 20,
              "minLength": 1,
              "type": "string"
            },
            "maxItems": 10000,
            "type": "array"
          }
        },
        "required": [
          "bank_account_id",
          "file_base64"
        ],
        "type": "object"
      },
      "BankStatementZenginCsvImportResult": {
        "description": "A 全銀 入出金取引明細 CSV read and self-checked against its trailer. preview writes nothing; commit writes the `new` rows.",
        "properties": {
          "duplicateCount": {
            "type": "integer"
          },
          "encoding": {
            "enum": [
              "utf-8",
              "shift_jis"
            ],
            "type": "string"
          },
          "importBatchId": {
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "insertedCount": {
            "description": "0 on preview",
            "type": "integer"
          },
          "mode": {
            "enum": [
              "preview",
              "commit"
            ],
            "type": "string"
          },
          "newCount": {
            "type": "integer"
          },
          "rows": {
            "items": {
              "properties": {
                "balance": {
                  "description": "Running balance from 取引前残高",
                  "type": "integer"
                },
                "depositAmount": {
                  "type": "integer"
                },
                "description": {
                  "type": "string"
                },
                "duplicateReason": {
                  "enum": [
                    "provider_transaction_id",
                    "import_hash",
                    "same_date_amount_balance",
                    null
                  ],
                  "nullable": true,
                  "type": "string"
                },
                "inquiryNumber": {
                  "description": "照会番号",
                  "type": "string"
                },
                "lineNo": {
                  "type": "integer"
                },
                "payoutProvider": {
                  "enum": [
                    "paypay",
                    "square",
                    "stripe",
                    null
                  ],
                  "nullable": true,
                  "type": "string"
                },
                "status": {
                  "enum": [
                    "new",
                    "duplicate"
                  ],
                  "type": "string"
                },
                "transactionDate": {
                  "description": "YYYYMMDD (勘定日)",
                  "type": "integer"
                },
                "transactionType": {
                  "type": "string"
                },
                "valueDate": {
                  "description": "YYYYMMDD (起算日)",
                  "nullable": true,
                  "type": "integer"
                },
                "withdrawalAmount": {
                  "type": "integer"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "statement": {
            "properties": {
              "accountNumberLast4": {
                "type": "string"
              },
              "bankCode": {
                "example": "0310",
                "type": "string"
              },
              "bankName": {
                "type": "string"
              },
              "branchName": {
                "type": "string"
              },
              "closingBalance": {
                "type": "integer"
              },
              "depositCount": {
                "type": "integer"
              },
              "depositTotal": {
                "type": "integer"
              },
              "openingBalance": {
                "type": "integer"
              },
              "periodFrom": {
                "description": "YYYYMMDD",
                "nullable": true,
                "type": "integer"
              },
              "periodTo": {
                "description": "YYYYMMDD",
                "nullable": true,
                "type": "integer"
              },
              "withdrawalCount": {
                "type": "integer"
              },
              "withdrawalTotal": {
                "type": "integer"
              }
            },
            "type": "object"
          }
        },
        "type": "object"
      },
      "BankStatementsInitResponse": {
        "description": "Composite response for the bank statements page — transactions, overview, and accounts in one call (v5.15)",
        "properties": {
          "data": {
            "properties": {
              "bankAccounts": {
                "description": "Bank accounts with latest balance and connection status",
                "items": {
                  "type": "object"
                },
                "type": "array"
              },
              "overview": {
                "allOf": [
                  {
                    "$ref": "#/components/schemas/BankStatementOverview"
                  }
                ],
                "description": "Same shape as GET /bank-statements/overview data; null when that fetch failed",
                "nullable": true
              },
              "transactions": {
                "description": "Paginated bank statement transactions (include_linked_counts=true)",
                "nullable": true,
                "properties": {
                  "items": {
                    "items": {
                      "$ref": "#/components/schemas/BankStatement"
                    },
                    "type": "array"
                  },
                  "pagination": {
                    "properties": {
                      "currentPage": {
                        "example": 1,
                        "type": "integer"
                      },
                      "hasNext": {
                        "example": true,
                        "type": "boolean"
                      },
                      "hasPrevious": {
                        "example": false,
                        "type": "boolean"
                      },
                      "pageSize": {
                        "example": 20,
                        "type": "integer"
                      },
                      "totalItems": {
                        "example": 129,
                        "type": "integer"
                      },
                      "totalPages": {
                        "example": 7,
                        "type": "integer"
                      }
                    },
                    "type": "object"
                  }
                },
                "type": "object"
              }
            },
            "type": "object"
          },
          "meta": {
            "properties": {
              "cached": {
                "description": "Whether response was served from memory cache",
                "type": "boolean"
              },
              "durationMs": {
                "description": "Total query time in milliseconds",
                "example": 280,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "type": "object"
      },
      "BankSyncLog": {
        "properties": {
          "completedAt": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "connectionId": {
            "format": "uuid",
            "type": "string"
          },
          "dateFrom": {
            "format": "date",
            "nullable": true,
            "type": "string"
          },
          "dateTo": {
            "format": "date",
            "nullable": true,
            "type": "string"
          },
          "durationMs": {
            "nullable": true,
            "type": "integer"
          },
          "errorMessage": {
            "nullable": true,
            "type": "string"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "startedAt": {
            "format": "date-time",
            "type": "string"
          },
          "status": {
            "enum": [
              "started",
              "success",
              "partial",
              "error"
            ],
            "type": "string"
          },
          "syncType": {
            "enum": [
              "manual",
              "scheduled",
              "webhook"
            ],
            "type": "string"
          },
          "transactionsDuplicated": {
            "type": "integer"
          },
          "transactionsFetched": {
            "type": "integer"
          },
          "transactionsInserted": {
            "type": "integer"
          }
        },
        "type": "object"
      },
      "BatchActivityItem": {
        "description": "Single activity item within a batch. Use camelCase for all fields.",
        "properties": {
          "actionLabel": {
            "maxLength": 255,
            "type": "string"
          },
          "actionType": {
            "enum": [
              "document_view",
              "document_edit",
              "document_create",
              "document_delete",
              "document_generate",
              "document_download",
              "document_print",
              "document_send",
              "document_share",
              "document_sign",
              "document_stamp",
              "document_archive",
              "document_restore",
              "document_duplicate",
              "document_update",
              "document_lock",
              "document_unlock",
              "document_void",
              "settings_company",
              "settings_accounting",
              "settings_auth",
              "settings_inkan",
              "settings_signature",
              "settings_profile",
              "settings_notification",
              "settings_payment",
              "settings_integration",
              "settings_export",
              "settings_import",
              "journal_entry",
              "journal_view",
              "journal_delete",
              "journal_approve",
              "journal_reject",
              "bank_reconcile",
              "fiscal_period",
              "account_create",
              "account_edit",
              "account_delete",
              "account_view",
              "trial_balance_view",
              "trial_balance_export",
              "report_view",
              "report_generate",
              "report_export",
              "report_print",
              "report_schedule",
              "client_create",
              "client_edit",
              "client_delete",
              "client_view",
              "ai_chat",
              "ai_suggestion_accept",
              "ai_suggestion_reject",
              "ai_reconcile",
              "ai_analyze",
              "page_visit",
              "session_start",
              "session_end",
              "session_resume",
              "tab_switch",
              "modal_open",
              "modal_close",
              "search_execute",
              "filter_apply",
              "sort_change",
              "form_submit",
              "form_save_draft",
              "form_validation_error",
              "error_occurred",
              "api_error",
              "network_error",
              "login",
              "logout",
              "password_change",
              "mfa_enable",
              "mfa_disable",
              "bulk_upload",
              "bulk_delete",
              "csv_import",
              "csv_export",
              "other"
            ],
            "type": "string"
          },
          "durationMs": {
            "minimum": 0,
            "type": "integer"
          },
          "entityId": {
            "description": "Valid UUID v4 only. Omit for page views without DB entity.",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "entityName": {
            "maxLength": 255,
            "type": "string"
          },
          "entityType": {
            "description": "Entity type: document, journal, page, etc.",
            "maxLength": 50,
            "type": "string"
          },
          "errorMessage": {
            "maxLength": 1000,
            "type": "string"
          },
          "isError": {
            "type": "boolean"
          },
          "metadata": {
            "type": "object"
          },
          "route": {
            "maxLength": 255,
            "type": "string"
          },
          "routeParams": {
            "type": "object"
          },
          "sequenceNumber": {
            "minimum": 0,
            "type": "integer"
          },
          "timestamp": {
            "format": "date-time",
            "type": "string"
          }
        },
        "required": [
          "actionType",
          "actionLabel",
          "route"
        ],
        "type": "object"
      },
      "BatchAwardXPRequest": {
        "properties": {
          "events": {
            "items": {
              "$ref": "#/components/schemas/AwardXPRequest"
            },
            "maxItems": 50,
            "minItems": 1,
            "type": "array"
          }
        },
        "required": [
          "events"
        ],
        "type": "object"
      },
      "BatchAwardXPResponse": {
        "properties": {
          "details": {
            "items": {
              "properties": {
                "event_type": {
                  "type": "string"
                },
                "reason": {
                  "type": "string"
                },
                "skipped": {
                  "type": "boolean"
                },
                "xp_awarded": {
                  "type": "integer"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "events_processed": {
            "example": 5,
            "type": "integer"
          },
          "events_skipped": {
            "example": 0,
            "type": "integer"
          },
          "leveled_up": {
            "type": "boolean"
          },
          "new_level": {
            "nullable": true,
            "type": "integer"
          },
          "total_xp_awarded": {
            "example": 100,
            "type": "integer"
          }
        },
        "type": "object"
      },
      "BatchCalculationRequest": {
        "description": "Batch salary calculation request (一括給与計算リクエスト)",
        "properties": {
          "employees": {
            "items": {
              "properties": {
                "dependents": {
                  "default": 0,
                  "example": 2,
                  "maximum": 20,
                  "minimum": 0,
                  "type": "integer"
                },
                "employee_id": {
                  "example": "emp1",
                  "type": "string"
                },
                "gross_salary": {
                  "example": 350000,
                  "minimum": 0,
                  "type": "number"
                },
                "social_insurance": {
                  "default": 0,
                  "example": 50000,
                  "minimum": 0,
                  "type": "number"
                },
                "tax_column": {
                  "enum": [
                    "kou",
                    "otsu"
                  ],
                  "example": "kou",
                  "type": "string"
                }
              },
              "required": [
                "employee_id",
                "gross_salary",
                "tax_column"
              ],
              "type": "object"
            },
            "minItems": 1,
            "type": "array"
          },
          "month": {
            "example": 12,
            "maximum": 12,
            "minimum": 1,
            "type": "integer"
          },
          "year": {
            "example": 2025,
            "type": "integer"
          }
        },
        "required": [
          "employees"
        ],
        "type": "object"
      },
      "BatchCalculationResult": {
        "description": "Batch calculation result (一括計算結果)",
        "properties": {
          "results": {
            "items": {
              "properties": {
                "employeeId": {
                  "example": "emp1",
                  "type": "string"
                },
                "error": {
                  "nullable": true,
                  "type": "string"
                },
                "netSalary": {
                  "example": 293910,
                  "type": "number"
                },
                "taxableIncome": {
                  "example": 300000,
                  "type": "number"
                },
                "withholdingTax": {
                  "example": 6090,
                  "type": "number"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "summary": {
            "properties": {
              "errorCount": {
                "example": 0,
                "type": "integer"
              },
              "successCount": {
                "example": 2,
                "type": "integer"
              },
              "totalGross": {
                "example": 600000,
                "type": "number"
              },
              "totalNet": {
                "example": 503360,
                "type": "number"
              },
              "totalWithholding": {
                "example": 11640,
                "type": "number"
              }
            },
            "type": "object"
          }
        },
        "type": "object"
      },
      "BatchCategorizeRequest": {
        "example": {
          "items": [
            {
              "amount": 3000,
              "description": "高速代",
              "id": "item-1",
              "vendor": "NEXCO"
            },
            {
              "amount": 5000,
              "description": "給油",
              "id": "item-2",
              "vendor": "ENEOS"
            }
          ]
        },
        "properties": {
          "items": {
            "items": {
              "properties": {
                "amount": {
                  "minimum": 0,
                  "type": "number"
                },
                "description": {
                  "maxLength": 2000,
                  "type": "string"
                },
                "id": {
                  "description": "Unique item identifier",
                  "type": "string"
                },
                "vendor": {
                  "maxLength": 500,
                  "type": "string"
                }
              },
              "required": [
                "id"
              ],
              "type": "object"
            },
            "maxItems": 100,
            "type": "array"
          }
        },
        "required": [
          "items"
        ],
        "type": "object"
      },
      "BatchItemResult": {
        "description": "Per-item result with HTTP-like status code (industry standard pattern)",
        "properties": {
          "code": {
            "description": "HTTP-like status: 200=success, 404=not found, 403=forbidden",
            "example": 200,
            "type": "integer"
          },
          "data": {
            "$ref": "#/components/schemas/DocumentLinkedDocumentsResponse"
          },
          "error": {
            "description": "Error message if code != 200",
            "type": "string"
          }
        },
        "type": "object"
      },
      "BatchLinkedDocumentsResponse": {
        "description": "Batch response with per-item status codes (Facebook/Google pattern)",
        "properties": {
          "_meta": {
            "properties": {
              "batchId": {
                "description": "Unique batch ID for tracing",
                "type": "string"
              },
              "processingTimeMs": {
                "description": "Processing time in milliseconds",
                "type": "integer"
              }
            },
            "type": "object"
          },
          "failedCount": {
            "description": "Documents that failed or not found",
            "type": "integer"
          },
          "processedCount": {
            "description": "Documents successfully processed",
            "type": "integer"
          },
          "results": {
            "additionalProperties": {
              "$ref": "#/components/schemas/BatchItemResult"
            },
            "description": "Results keyed by document ID",
            "type": "object"
          },
          "totalDocuments": {
            "description": "Total documents requested",
            "type": "integer"
          }
        },
        "type": "object"
      },
      "BatchProcessApiResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/BatchProcessResponse"
          },
          "message": {
            "example": "Batch processing completed successfully",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "BatchProcessOptions": {
        "properties": {
          "applyRules": {
            "description": "Apply existing automation rules",
            "example": true,
            "type": "boolean"
          },
          "autoJournalize": {
            "description": "Enable automatic journal entry generation",
            "example": false,
            "type": "boolean"
          },
          "autoMatch": {
            "description": "Enable automatic document matching",
            "example": true,
            "type": "boolean"
          },
          "confidenceThreshold": {
            "description": "Minimum confidence threshold for automation",
            "example": 0.8,
            "format": "double",
            "maximum": 1,
            "minimum": 0,
            "type": "number"
          }
        },
        "type": "object"
      },
      "BatchProcessRequest": {
        "properties": {
          "options": {
            "$ref": "#/components/schemas/BatchProcessOptions"
          },
          "transactionIds": {
            "description": "List of transaction IDs to process",
            "example": [
              "txn_001",
              "txn_002",
              "txn_003"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          }
        },
        "required": [
          "transactionIds"
        ],
        "type": "object"
      },
      "BatchProcessResponse": {
        "properties": {
          "processed": {
            "description": "Number of transactions processed",
            "example": 3,
            "type": "integer"
          },
          "results": {
            "description": "Processing results for each transaction",
            "items": {
              "$ref": "#/components/schemas/BatchProcessResult"
            },
            "type": "array"
          }
        },
        "required": [
          "processed",
          "results"
        ],
        "type": "object"
      },
      "BatchProcessResult": {
        "properties": {
          "appliedRule": {
            "description": "Applied rule name (if applicable)",
            "example": "Amazon購入自動分類",
            "type": "string"
          },
          "confidence": {
            "description": "Processing confidence score",
            "example": 0.92,
            "format": "double",
            "maximum": 1,
            "minimum": 0,
            "type": "number"
          },
          "matchedDocument": {
            "description": "Matched document ID (if applicable)",
            "example": "doc_456",
            "type": "string"
          },
          "reason": {
            "description": "Processing result reason",
            "example": "高い信頼度で文書マッチングが完了しました",
            "type": "string"
          },
          "status": {
            "$ref": "#/components/schemas/BatchProcessStatus"
          },
          "suggestedJournal": {
            "$ref": "#/components/schemas/JournalEntry"
          },
          "suggestions": {
            "description": "Additional suggestions",
            "items": {
              "properties": {
                "action": {
                  "example": "手動確認",
                  "type": "string"
                },
                "reason": {
                  "example": "金額が大きいため確認をお勧めします",
                  "type": "string"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "transactionId": {
            "description": "Transaction ID",
            "example": "txn_001",
            "type": "string"
          }
        },
        "required": [
          "transactionId",
          "status"
        ],
        "type": "object"
      },
      "BatchProcessStatus": {
        "description": "Batch processing result status",
        "enum": [
          "matched",
          "rule_applied",
          "needs_review",
          "error"
        ],
        "example": "matched",
        "type": "string"
      },
      "BatchRecordRequest": {
        "description": "Request body for batch recording activities. Use camelCase for all fields.",
        "properties": {
          "activities": {
            "description": "Array of activities to record (max 100)",
            "items": {
              "$ref": "#/components/schemas/BatchActivityItem"
            },
            "maxItems": 100,
            "minItems": 1,
            "type": "array"
          },
          "browser": {
            "maxLength": 50,
            "type": "string"
          },
          "companyId": {
            "format": "uuid",
            "type": "string"
          },
          "deviceType": {
            "enum": [
              "desktop",
              "tablet",
              "mobile"
            ],
            "type": "string"
          },
          "os": {
            "maxLength": 50,
            "type": "string"
          },
          "sessionId": {
            "maxLength": 64,
            "type": "string"
          },
          "userAgent": {
            "maxLength": 500,
            "type": "string"
          }
        },
        "required": [
          "activities"
        ],
        "type": "object"
      },
      "BatchRecordResponse": {
        "properties": {
          "activities": {
            "items": {
              "$ref": "#/components/schemas/UserActivity"
            },
            "type": "array"
          },
          "batch_id": {
            "format": "uuid",
            "type": "string"
          },
          "duplicate_count": {
            "description": "Number of duplicate activities removed (deduplicated by session_id + route + timestamp)",
            "type": "integer"
          },
          "errors": {
            "items": {
              "properties": {
                "error": {
                  "type": "string"
                },
                "index": {
                  "type": "integer"
                }
              },
              "type": "object"
            },
            "nullable": true,
            "type": "array"
          },
          "failed_count": {
            "description": "Number of activities that failed to record",
            "type": "integer"
          },
          "recorded_count": {
            "description": "Number of activities successfully recorded",
            "type": "integer"
          }
        },
        "type": "object"
      },
      "BatchTileRequest": {
        "properties": {
          "apiCode": {
            "$ref": "#/components/schemas/MLITGISAPICode"
          },
          "cluster": {
            "description": "Enable point clustering for dense datasets",
            "example": true,
            "type": "boolean"
          },
          "clusterProperty": {
            "description": "Property to use for clustering (e.g., \"price\")",
            "example": "price",
            "type": "string"
          },
          "params": {
            "additionalProperties": {
              "type": "string"
            },
            "description": "Additional API parameters",
            "type": "object"
          },
          "simplify": {
            "description": "Enable geometry simplification for better performance",
            "example": true,
            "type": "boolean"
          },
          "tiles": {
            "description": "Array of tile coordinates (maximum 25 tiles)",
            "items": {
              "$ref": "#/components/schemas/TileRequest"
            },
            "maxItems": 25,
            "type": "array"
          }
        },
        "required": [
          "apiCode",
          "tiles"
        ],
        "type": "object"
      },
      "BatchTileResponse": {
        "properties": {
          "data": {
            "properties": {
              "stats": {
                "$ref": "#/components/schemas/BatchTileStats"
              },
              "tiles": {
                "items": {
                  "$ref": "#/components/schemas/TileResult"
                },
                "type": "array"
              }
            },
            "type": "object"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "BatchTileStats": {
        "properties": {
          "avgTimePerTile": {
            "description": "Average time per tile in milliseconds",
            "example": 37,
            "type": "integer"
          },
          "cached": {
            "description": "Number of tiles served from cache",
            "example": 2,
            "type": "integer"
          },
          "failed": {
            "description": "Number of tiles that failed to load",
            "example": 0,
            "type": "integer"
          },
          "fetched": {
            "description": "Number of tiles fetched from API",
            "example": 2,
            "type": "integer"
          },
          "total": {
            "description": "Total number of tiles requested",
            "example": 4,
            "type": "integer"
          },
          "totalTimeMs": {
            "description": "Total processing time in milliseconds",
            "example": 150,
            "type": "integer"
          }
        },
        "required": [
          "total",
          "cached",
          "fetched",
          "failed",
          "totalTimeMs",
          "avgTimePerTile"
        ],
        "type": "object"
      },
      "BilingualLabel": {
        "properties": {
          "en": {
            "type": "string"
          },
          "ja": {
            "type": "string"
          }
        },
        "type": "object"
      },
      "BookingSuggestion": {
        "description": "「前回と同じ」 for one bank row: the way the tenant booked the same payee before (same amount when it recurs). `varied` = the comparable history was booked more than one way — every way is listed in `variants`.",
        "properties": {
          "amount": {
            "description": "Absolute bank amount",
            "type": "number"
          },
          "bankTransactionId": {
            "format": "uuid",
            "type": "string"
          },
          "basis": {
            "description": "`payout_clearing` = a PayPay settlement with no sizeable precedent, parked Dr 普通預金 / Cr 105 未収入金 「PayPay入金 (精算待ち)」 until the settlement statement splits it. `integration_payout` = the deposit is a payout an integration batch already drafted (Dr 普通預金 net / Dr 支払手数料 fee / Cr 105 gross); approve it in 連携バッチ (`post` is null)",
            "enum": [
              "same_amount",
              "single_account",
              "payout_clearing",
              "integration_payout",
              null
            ],
            "nullable": true,
            "type": "string"
          },
          "booked": {
            "type": "boolean"
          },
          "description": {
            "type": "string"
          },
          "direction": {
            "enum": [
              "deposit",
              "withdrawal"
            ],
            "type": "string"
          },
          "documentCandidates": {
            "items": {
              "properties": {
                "amount": {
                  "type": "number"
                },
                "date": {
                  "nullable": true,
                  "type": "string"
                },
                "dayDiff": {
                  "type": "integer"
                },
                "documentId": {
                  "format": "uuid",
                  "type": "string"
                },
                "documentName": {
                  "type": "string"
                },
                "documentType": {
                  "type": "string"
                }
              },
              "required": [
                "documentId",
                "documentName",
                "documentType",
                "amount",
                "date",
                "dayDiff"
              ],
              "type": "object"
            },
            "type": "array"
          },
          "groupKey": {
            "description": "Rows sharing a key share one proposal (bulk apply)",
            "nullable": true,
            "type": "string"
          },
          "historyCount": {
            "type": "integer"
          },
          "integrationPayout": {
            "description": "basis integration_payout only: the payout batch (BE ADR-0021) this deposit settles",
            "properties": {
              "batchLogId": {
                "format": "uuid",
                "type": "string"
              },
              "journalEntryIds": {
                "items": {
                  "format": "uuid",
                  "type": "string"
                },
                "type": "array"
              },
              "payoutId": {
                "type": "string"
              },
              "provider": {
                "enum": [
                  "paypay",
                  "square",
                  "stripe"
                ],
                "type": "string"
              },
              "source": {
                "enum": [
                  "tsumagoi",
                  "stripe"
                ],
                "type": "string"
              },
              "status": {
                "enum": [
                  "drafted",
                  "approved"
                ],
                "type": "string"
              }
            },
            "required": [
              "batchLogId",
              "source",
              "provider",
              "payoutId",
              "status",
              "journalEntryIds"
            ],
            "type": "object"
          },
          "latestEntryDate": {
            "nullable": true,
            "type": "integer"
          },
          "latestEntryNumber": {
            "nullable": true,
            "type": "string"
          },
          "lines": {
            "items": {
              "properties": {
                "accountCode": {
                  "example": "514",
                  "type": "string"
                },
                "accountName": {
                  "example": "支払手数料",
                  "type": "string"
                },
                "amount": {
                  "example": 130,
                  "type": "number"
                },
                "side": {
                  "enum": [
                    "debit",
                    "credit"
                  ],
                  "type": "string"
                },
                "taxCode": {
                  "description": "journal_entry_lines.tax_code (1 課税10% … 5 対象外)",
                  "nullable": true,
                  "type": "integer"
                },
                "taxLabel": {
                  "example": "課税10%",
                  "nullable": true,
                  "type": "string"
                }
              },
              "required": [
                "side",
                "accountCode",
                "accountName",
                "amount",
                "taxCode",
                "taxLabel"
              ],
              "type": "object"
            },
            "type": "array"
          },
          "matches": {
            "description": "Entries behind the proposed way of booking",
            "type": "integer"
          },
          "post": {
            "description": "`create_expense` → POST /reconciliation/create-expense (preview first) with accountCode + taxType; `create_compound_journal` → POST /reconciliation/create-compound-journal with entries.",
            "nullable": true,
            "properties": {
              "accountCode": {
                "type": "string"
              },
              "description": {
                "example": "賃借料 店舗（サンプル管理事務所）10月分",
                "type": "string"
              },
              "entries": {
                "items": {
                  "properties": {
                    "accountCode": {
                      "type": "string"
                    },
                    "accountName": {
                      "type": "string"
                    },
                    "creditAmount": {
                      "type": "number"
                    },
                    "debitAmount": {
                      "type": "number"
                    },
                    "taxCategory": {
                      "nullable": true,
                      "type": "string"
                    }
                  },
                  "required": [
                    "accountCode",
                    "accountName",
                    "debitAmount",
                    "creditAmount",
                    "taxCategory"
                  ],
                  "type": "object"
                },
                "type": "array"
              },
              "entryType": {
                "enum": [
                  "expense",
                  "revenue"
                ],
                "type": "string"
              },
              "path": {
                "enum": [
                  "create_expense",
                  "create_compound_journal"
                ],
                "type": "string"
              },
              "taxType": {
                "nullable": true,
                "type": "integer"
              }
            },
            "required": [
              "path",
              "description"
            ],
            "type": "object"
          },
          "posted": {
            "nullable": true,
            "properties": {
              "lines": {
                "items": {
                  "properties": {
                    "accountCode": {
                      "example": "514",
                      "type": "string"
                    },
                    "accountName": {
                      "example": "支払手数料",
                      "type": "string"
                    },
                    "amount": {
                      "example": 130,
                      "type": "number"
                    },
                    "side": {
                      "enum": [
                        "debit",
                        "credit"
                      ],
                      "type": "string"
                    },
                    "taxCode": {
                      "description": "journal_entry_lines.tax_code (1 課税10% … 5 対象外)",
                      "nullable": true,
                      "type": "integer"
                    },
                    "taxLabel": {
                      "example": "課税10%",
                      "nullable": true,
                      "type": "string"
                    }
                  },
                  "required": [
                    "side",
                    "accountCode",
                    "accountName",
                    "amount",
                    "taxCode",
                    "taxLabel"
                  ],
                  "type": "object"
                },
                "type": "array"
              },
              "matchesHistory": {
                "type": "boolean"
              }
            },
            "required": [
              "lines",
              "matchesHistory"
            ],
            "type": "object"
          },
          "status": {
            "enum": [
              "suggested",
              "varied",
              "reference",
              "document_driven",
              "none"
            ],
            "type": "string"
          },
          "transactionDate": {
            "description": "YYYYMMDD",
            "type": "integer"
          },
          "variants": {
            "items": {
              "properties": {
                "chosen": {
                  "type": "boolean"
                },
                "count": {
                  "type": "integer"
                },
                "latestEntryDate": {
                  "type": "integer"
                },
                "latestEntryNumber": {
                  "type": "string"
                },
                "lines": {
                  "items": {
                    "properties": {
                      "accountCode": {
                        "example": "514",
                        "type": "string"
                      },
                      "accountName": {
                        "example": "支払手数料",
                        "type": "string"
                      },
                      "amount": {
                        "example": 130,
                        "type": "number"
                      },
                      "side": {
                        "enum": [
                          "debit",
                          "credit"
                        ],
                        "type": "string"
                      },
                      "taxCode": {
                        "description": "journal_entry_lines.tax_code (1 課税10% … 5 対象外)",
                        "nullable": true,
                        "type": "integer"
                      },
                      "taxLabel": {
                        "example": "課税10%",
                        "nullable": true,
                        "type": "string"
                      }
                    },
                    "required": [
                      "side",
                      "accountCode",
                      "accountName",
                      "amount",
                      "taxCode",
                      "taxLabel"
                    ],
                    "type": "object"
                  },
                  "type": "array"
                },
                "post": {
                  "description": "`create_expense` → POST /reconciliation/create-expense (preview first) with accountCode + taxType; `create_compound_journal` → POST /reconciliation/create-compound-journal with entries.",
                  "nullable": true,
                  "properties": {
                    "accountCode": {
                      "type": "string"
                    },
                    "description": {
                      "example": "賃借料 店舗（サンプル管理事務所）10月分",
                      "type": "string"
                    },
                    "entries": {
                      "items": {
                        "properties": {
                          "accountCode": {
                            "type": "string"
                          },
                          "accountName": {
                            "type": "string"
                          },
                          "creditAmount": {
                            "type": "number"
                          },
                          "debitAmount": {
                            "type": "number"
                          },
                          "taxCategory": {
                            "nullable": true,
                            "type": "string"
                          }
                        },
                        "required": [
                          "accountCode",
                          "accountName",
                          "debitAmount",
                          "creditAmount",
                          "taxCategory"
                        ],
                        "type": "object"
                      },
                      "type": "array"
                    },
                    "entryType": {
                      "enum": [
                        "expense",
                        "revenue"
                      ],
                      "type": "string"
                    },
                    "path": {
                      "enum": [
                        "create_expense",
                        "create_compound_journal"
                      ],
                      "type": "string"
                    },
                    "taxType": {
                      "nullable": true,
                      "type": "integer"
                    }
                  },
                  "required": [
                    "path",
                    "description"
                  ],
                  "type": "object"
                }
              },
              "required": [
                "lines",
                "count",
                "latestEntryNumber",
                "latestEntryDate",
                "chosen",
                "post"
              ],
              "type": "object"
            },
            "type": "array"
          }
        },
        "required": [
          "bankTransactionId",
          "transactionDate",
          "description",
          "amount",
          "direction",
          "booked",
          "status",
          "basis",
          "historyCount",
          "matches",
          "latestEntryNumber",
          "latestEntryDate",
          "lines",
          "post",
          "variants",
          "groupKey",
          "posted",
          "documentCandidates"
        ],
        "type": "object"
      },
      "BookingSuggestionsResponse": {
        "properties": {
          "data": {
            "properties": {
              "suggestions": {
                "items": {
                  "$ref": "#/components/schemas/BookingSuggestion"
                },
                "type": "array"
              },
              "total": {
                "description": "未仕訳 rows under the filters (the list may be capped by limit)",
                "type": "integer"
              }
            },
            "required": [
              "suggestions",
              "total"
            ],
            "type": "object"
          },
          "message": {
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "BooksShareAccessEvent": {
        "properties": {
          "action": {
            "enum": [
              "resolve",
              "gate",
              "audit_pack",
              "memos",
              "evidence_list",
              "evidence_file",
              "filing_data",
              "filing_data_pdf",
              "report_data",
              "ask",
              "unlock_ok",
              "unlock_fail",
              "cta_click"
            ],
            "type": "string"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "ip": {
            "nullable": true,
            "type": "string"
          },
          "occurred_at": {
            "format": "date-time",
            "type": "string"
          },
          "user_agent": {
            "nullable": true,
            "type": "string"
          }
        },
        "type": "object"
      },
      "BooksShareCreated": {
        "description": "Share link created — raw token is returned once",
        "properties": {
          "allow_audit_pack": {
            "type": "boolean"
          },
          "created_at": {
            "format": "date-time",
            "type": "string"
          },
          "expires_at": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "fiscal_year": {
            "nullable": true,
            "type": "integer"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "label": {
            "nullable": true,
            "type": "string"
          },
          "password_protected": {
            "type": "boolean"
          },
          "token": {
            "description": "64-char hex; shown only on create",
            "type": "string"
          }
        },
        "type": "object"
      },
      "Bounds": {
        "properties": {
          "ne": {
            "$ref": "#/components/schemas/Coordinates",
            "description": "Northeast corner coordinates"
          },
          "sw": {
            "$ref": "#/components/schemas/Coordinates",
            "description": "Southwest corner coordinates"
          }
        },
        "required": [
          "sw",
          "ne"
        ],
        "type": "object"
      },
      "BudgetLimit": {
        "description": "Budget limit for purchase recommendations",
        "enum": [
          100000,
          300000
        ],
        "example": 300000,
        "type": "integer"
      },
      "BulkApplyExchangeRateRequest": {
        "properties": {
          "exchange_rate_id": {
            "description": "Exchange rate identifier to apply",
            "example": "789e0123-e45b-67c8-d901-234567890123",
            "format": "uuid",
            "type": "string"
          },
          "expense_ids": {
            "description": "Array of expense identifiers to apply exchange rate to",
            "example": [
              "123e4567-e89b-12d3-a456-426614174000",
              "456e7890-f12a-34b5-c678-901234567890"
            ],
            "items": {
              "format": "uuid",
              "type": "string"
            },
            "type": "array"
          }
        },
        "required": [
          "expense_ids",
          "exchange_rate_id"
        ],
        "type": "object"
      },
      "BulkBankStatementResponse": {
        "properties": {
          "data": {
            "properties": {
              "count": {
                "description": "Number of items successfully inserted",
                "example": 8,
                "type": "integer"
              },
              "duplicates_skipped": {
                "description": "Number of duplicates that were skipped",
                "example": 2,
                "type": "integer"
              },
              "inserted": {
                "description": "Items that were successfully inserted (optional)",
                "items": {
                  "$ref": "#/components/schemas/BankStatement"
                },
                "type": "array"
              },
              "message": {
                "description": "Human-readable summary message",
                "example": "8 items created, 2 duplicates skipped",
                "type": "string"
              },
              "skipped_details": {
                "description": "Detailed information about each skipped duplicate",
                "items": {
                  "properties": {
                    "index": {
                      "description": "Index of duplicate item in original request array",
                      "example": 3,
                      "type": "integer"
                    },
                    "item_preview": {
                      "description": "Preview of the duplicate item for debugging",
                      "type": "object"
                    },
                    "key_fields": {
                      "description": "Fields that caused the duplicate detection",
                      "properties": {
                        "balance": {
                          "example": 1250000,
                          "type": "number"
                        },
                        "deposit_amount": {
                          "example": 300000,
                          "type": "number"
                        },
                        "transaction_date": {
                          "example": 20240115,
                          "type": "integer"
                        },
                        "withdrawal_amount": {
                          "example": 0,
                          "type": "number"
                        }
                      },
                      "type": "object"
                    },
                    "reason": {
                      "description": "Why the item was identified as duplicate",
                      "enum": [
                        "duplicate_in_database",
                        "duplicate_in_batch"
                      ],
                      "example": "duplicate_in_database",
                      "type": "string"
                    }
                  },
                  "type": "object"
                },
                "type": "array"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Bank statements created successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "BulkCreateBankStatementsRequest": {
        "properties": {
          "import_session_id": {
            "description": "Client import-session id: every request of one import session shares one import_batch_id.",
            "pattern": "^[\\w-]{1,100}$",
            "type": "string"
          },
          "import_source": {
            "description": "How the rows were obtained. `paste` (コピペ) stamps source, import_hash, import_batch_id and raw_description, and merges a row into a stored csv_import row of the same movement (same account, date, amounts, and balance when both have one) by updating that row's description instead of inserting. Omitted = rows keep the column default (`manual`).",
            "enum": [
              "paste",
              "csv_import"
            ],
            "type": "string"
          },
          "statements": {
            "description": "Array of bank statements to create",
            "items": {
              "allOf": [
                {
                  "$ref": "#/components/schemas/CreateBankStatementRequest"
                },
                {
                  "properties": {
                    "raw_description": {
                      "description": "The statement line this row was parsed from, stored verbatim as raw_description.",
                      "maxLength": 2000,
                      "type": "string"
                    }
                  },
                  "type": "object"
                }
              ]
            },
            "maxItems": 100,
            "minItems": 1,
            "type": "array"
          }
        },
        "required": [
          "statements"
        ],
        "type": "object"
      },
      "BulkDeleteDocumentsRequest": {
        "properties": {
          "documentIds": {
            "description": "Array of document UUIDs to delete",
            "example": [
              "uuid1",
              "uuid2",
              "uuid3"
            ],
            "items": {
              "format": "uuid",
              "type": "string"
            },
            "type": "array"
          }
        },
        "required": [
          "documentIds"
        ],
        "type": "object"
      },
      "BulkDeleteResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/BulkDeleteResult"
          },
          "message": {
            "example": "Bulk deletion completed",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "BulkDeleteResult": {
        "properties": {
          "deletedFiles": {
            "description": "Successfully deleted files with their details",
            "items": {
              "properties": {
                "fileId": {
                  "example": "123e4567-e89b-12d3-a456-426614174000",
                  "format": "uuid",
                  "type": "string"
                },
                "fileName": {
                  "example": "receipt_2024_01_15.jpg",
                  "type": "string"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "failedFiles": {
            "description": "Files that failed to delete with error details",
            "items": {
              "properties": {
                "error": {
                  "example": "File not found or access denied",
                  "type": "string"
                },
                "fileId": {
                  "example": "789e0123-e45b-67c8-d901-234567890123",
                  "format": "uuid",
                  "type": "string"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "failureCount": {
            "description": "Number of files that failed to delete",
            "example": 1,
            "type": "integer"
          },
          "successCount": {
            "description": "Number of successfully deleted files",
            "example": 4,
            "type": "integer"
          },
          "totalFiles": {
            "description": "Total number of files in the deletion request",
            "example": 5,
            "type": "integer"
          }
        },
        "required": [
          "deletedFiles",
          "failedFiles",
          "totalFiles",
          "successCount",
          "failureCount"
        ],
        "type": "object"
      },
      "BulkExchangeRateApplicationResponse": {
        "properties": {
          "data": {
            "properties": {
              "exchange_rate": {
                "description": "Applied exchange rate",
                "example": 150.25,
                "type": "number"
              },
              "exchange_rate_id": {
                "description": "Applied exchange rate identifier",
                "example": "789e0123-e45b-67c8-d901-234567890123",
                "format": "uuid",
                "type": "string"
              },
              "processed_count": {
                "description": "Number of expenses processed",
                "example": 5,
                "type": "integer"
              },
              "processed_expenses": {
                "description": "Array of processed expense identifiers",
                "example": [
                  "123e4567-e89b-12d3-a456-426614174000",
                  "456e7890-f12a-34b5-c678-901234567890"
                ],
                "items": {
                  "format": "uuid",
                  "type": "string"
                },
                "type": "array"
              },
              "total_converted_amount": {
                "description": "Total converted amount in Japanese Yen",
                "example": 75125,
                "type": "number"
              },
              "total_original_amount": {
                "description": "Total original amount in foreign currency",
                "example": 500,
                "type": "number"
              }
            },
            "required": [
              "processed_count",
              "exchange_rate_id",
              "total_original_amount",
              "total_converted_amount",
              "exchange_rate",
              "processed_expenses"
            ],
            "type": "object"
          },
          "message": {
            "example": "Bulk exchange rate applied successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "BulkGenerateRequest": {
        "properties": {
          "document_ids": {
            "description": "Array of document IDs to generate journal entries for",
            "example": [
              "123e4567-e89b-12d3-a456-426614174000",
              "456e7890-f12a-34b5-c678-901234567890"
            ],
            "items": {
              "format": "uuid",
              "type": "string"
            },
            "minItems": 1,
            "type": "array"
          }
        },
        "required": [
          "document_ids"
        ],
        "type": "object"
      },
      "BulkInvoiceVerificationRequest": {
        "properties": {
          "registration_numbers": {
            "description": "Array of invoice registration numbers to verify",
            "example": [
              "T1234567890123",
              "T9876543210987"
            ],
            "items": {
              "pattern": "^T\\d{13}$",
              "type": "string"
            },
            "maxItems": 100,
            "type": "array"
          }
        },
        "required": [
          "registration_numbers"
        ],
        "type": "object"
      },
      "BulkLockDocumentsRequest": {
        "properties": {
          "documentIds": {
            "description": "Array of document UUIDs to lock/unlock",
            "example": [
              "uuid1",
              "uuid2",
              "uuid3"
            ],
            "items": {
              "format": "uuid",
              "type": "string"
            },
            "type": "array"
          },
          "isLocked": {
            "description": "Set to true to lock, false to unlock",
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "documentIds",
          "isLocked"
        ],
        "type": "object"
      },
      "BulkOperationResponse": {
        "properties": {
          "data": {
            "properties": {
              "isLocked": {
                "example": true,
                "type": "boolean"
              },
              "success": {
                "example": true,
                "type": "boolean"
              },
              "updatedCount": {
                "example": 3,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "3 documents locked successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "type": "object"
      },
      "BulkPostResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/BulkPostResult"
          },
          "message": {
            "example": "Bulk post completed: 6 posted, 0 failed, 1 skipped",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "BulkPostResult": {
        "properties": {
          "failed": {
            "description": "Number of journal entries that failed to post",
            "example": 0,
            "minimum": 0,
            "type": "integer"
          },
          "posted": {
            "description": "Number of journal entries successfully posted",
            "example": 6,
            "minimum": 0,
            "type": "integer"
          },
          "results": {
            "description": "Detailed results for each journal entry",
            "items": {
              "properties": {
                "entryNumber": {
                  "description": "Journal entry number",
                  "example": "JE-2024-001",
                  "nullable": true,
                  "type": "string"
                },
                "error": {
                  "description": "Error message if failed or skipped",
                  "example": "No journal entry lines",
                  "nullable": true,
                  "type": "string"
                },
                "journalId": {
                  "description": "Journal entry ID",
                  "example": "789e0123-e45b-67c8-d901-234567890123",
                  "format": "uuid",
                  "type": "string"
                },
                "status": {
                  "description": "Result status for this journal entry",
                  "enum": [
                    "posted",
                    "failed",
                    "skipped"
                  ],
                  "example": "posted",
                  "type": "string"
                }
              },
              "required": [
                "journalId",
                "status"
              ],
              "type": "object"
            },
            "type": "array"
          },
          "skipped": {
            "description": "Number of journal entries skipped (e.g., no lines)",
            "example": 1,
            "minimum": 0,
            "type": "integer"
          },
          "totalDrafts": {
            "description": "Total number of draft journal entries found",
            "example": 7,
            "minimum": 0,
            "type": "integer"
          }
        },
        "required": [
          "totalDrafts",
          "posted",
          "failed",
          "skipped",
          "results"
        ],
        "type": "object"
      },
      "BulkUpdateProcessingStatusRequest": {
        "description": "Request body for bulk updating processing status (v4.34+)",
        "properties": {
          "processing_status": {
            "description": "New processing status to apply to all transactions",
            "example": "no_doc_required",
            "oneOf": [
              {
                "$ref": "#/components/schemas/ProcessingStatusEnum"
              },
              {
                "description": "Set to null to clear explicit status and revert to derived behavior",
                "type": "null"
              }
            ]
          },
          "transaction_ids": {
            "description": "Array of transaction UUIDs to update (max 100)",
            "example": [
              "550e8400-e29b-41d4-a716-446655440001",
              "550e8400-e29b-41d4-a716-446655440002"
            ],
            "items": {
              "format": "uuid",
              "type": "string"
            },
            "type": "array"
          }
        },
        "required": [
          "transaction_ids",
          "processing_status"
        ],
        "type": "object"
      },
      "BulkUpdateProcessingStatusResponse": {
        "description": "Response after bulk updating processing status (v4.34+)",
        "properties": {
          "data": {
            "properties": {
              "failedCount": {
                "description": "Number of transactions that failed to update",
                "example": 0,
                "type": "integer"
              },
              "results": {
                "description": "Individual results for each transaction",
                "items": {
                  "properties": {
                    "effectiveStatus": {
                      "$ref": "#/components/schemas/ProcessingStatusEnum"
                    },
                    "error": {
                      "type": "string"
                    },
                    "oldStatus": {
                      "oneOf": [
                        {
                          "$ref": "#/components/schemas/ProcessingStatusEnum"
                        },
                        {
                          "type": "null"
                        }
                      ]
                    },
                    "success": {
                      "type": "boolean"
                    },
                    "transactionId": {
                      "format": "uuid",
                      "type": "string"
                    }
                  },
                  "type": "object"
                },
                "type": "array"
              },
              "updatedCount": {
                "description": "Number of transactions successfully updated",
                "example": 5,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Updated 5 transactions",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "type": "object"
      },
      "BulkUploadResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/BulkUploadResult"
          },
          "message": {
            "example": "Bulk upload completed",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "BulkUploadResult": {
        "properties": {
          "failedFiles": {
            "description": "Files that failed to upload with error details",
            "items": {
              "properties": {
                "error": {
                  "example": "Unsupported file type",
                  "type": "string"
                },
                "fileName": {
                  "example": "invalid_file.txt",
                  "type": "string"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "failureCount": {
            "description": "Number of failed file uploads",
            "example": 1,
            "type": "integer"
          },
          "successCount": {
            "description": "Number of successfully uploaded files",
            "example": 4,
            "type": "integer"
          },
          "totalFiles": {
            "description": "Total number of files in the upload batch",
            "example": 5,
            "type": "integer"
          },
          "uploadedFiles": {
            "description": "Successfully uploaded files with database records",
            "items": {
              "$ref": "#/components/schemas/FileUpload"
            },
            "type": "array"
          }
        },
        "required": [
          "uploadedFiles",
          "failedFiles",
          "totalFiles",
          "successCount",
          "failureCount"
        ],
        "type": "object"
      },
      "BusinessType": {
        "description": "Type of business for establishment guidance",
        "enum": [
          "it",
          "consulting",
          "creative",
          "retail",
          "service",
          "other"
        ],
        "example": "it",
        "type": "string"
      },
      "BusinessTypeReference": {
        "properties": {
          "deemedPurchaseRate": {
            "description": "Deemed purchase rate percentage",
            "example": 50,
            "type": "number"
          },
          "description": {
            "description": "Business type description",
            "example": "運輸通信業、サービス業（飲食店業を除く）",
            "type": "string"
          },
          "label": {
            "description": "Business type label in Japanese",
            "example": "第五種事業（サービス業等）",
            "type": "string"
          },
          "value": {
            "description": "Business type value",
            "example": "service",
            "type": "string"
          }
        },
        "required": [
          "value",
          "label",
          "deemedPurchaseRate",
          "description"
        ],
        "type": "object"
      },
      "BusinessTypeReferenceResponse": {
        "properties": {
          "data": {
            "properties": {
              "businessTypes": {
                "items": {
                  "$ref": "#/components/schemas/BusinessTypeReference"
                },
                "type": "array"
              },
              "notes": {
                "example": [
                  "簡易課税は基準期間の課税売上高が5,000万円以下の場合に選択可能",
                  "選択は事前届出が必要（消費税簡易課税制度選択届出書）",
                  "一度選択すると2年間は変更不可"
                ],
                "items": {
                  "type": "string"
                },
                "type": "array"
              }
            },
            "type": "object"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "BuyerAttachment": {
        "description": "Represents a buyer attachment (発注書/納品書) uploaded to a document",
        "properties": {
          "attachmentType": {
            "description": "Type of buyer attachment",
            "enum": [
              "purchase_order",
              "delivery_note",
              "other"
            ],
            "example": "purchase_order",
            "type": "string"
          },
          "createdAt": {
            "description": "When the attachment was uploaded",
            "format": "date-time",
            "type": "string"
          },
          "description": {
            "description": "Optional description of the attachment",
            "example": "ABC株式会社からの発注書",
            "nullable": true,
            "type": "string"
          },
          "fileUpload": {
            "description": "Details of the uploaded file",
            "properties": {
              "createdAt": {
                "format": "date-time",
                "type": "string"
              },
              "fileName": {
                "example": "発注書_20260110.pdf",
                "type": "string"
              },
              "fileType": {
                "example": "pdf",
                "type": "string"
              },
              "fileUrl": {
                "format": "uri",
                "type": "string"
              },
              "id": {
                "format": "uuid",
                "type": "string"
              }
            },
            "type": "object"
          },
          "fileUploadId": {
            "description": "ID of the uploaded file",
            "example": "789e0123-e89b-12d3-a456-426614174002",
            "format": "uuid",
            "type": "string"
          },
          "id": {
            "description": "Unique identifier for the attachment",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "metadata": {
            "additionalProperties": true,
            "description": "Additional metadata",
            "nullable": true,
            "type": "object"
          },
          "relationshipId": {
            "description": "ID of the underlying relationship",
            "example": "456e7890-e89b-12d3-a456-426614174001",
            "format": "uuid",
            "type": "string"
          }
        },
        "required": [
          "id",
          "relationshipId",
          "fileUploadId",
          "attachmentType",
          "createdAt",
          "fileUpload"
        ],
        "type": "object"
      },
      "BuyerAttachmentsResponse": {
        "properties": {
          "data": {
            "items": {
              "$ref": "#/components/schemas/BuyerAttachment"
            },
            "type": "array"
          },
          "message": {
            "example": "Buyer attachments retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "type": "object"
      },
      "CacheStats": {
        "properties": {
          "hitRate": {
            "description": "Cache hit rate (0-1)",
            "example": 0.78125,
            "format": "double",
            "type": "number"
          },
          "hitRatePercent": {
            "description": "Cache hit rate as percentage",
            "example": "78.1%",
            "type": "string"
          },
          "hits": {
            "description": "Total cache hits",
            "example": 1250,
            "type": "integer"
          },
          "memoryUsage": {
            "description": "Formatted memory usage",
            "example": "125.67 MB",
            "type": "string"
          },
          "memoryUsageMB": {
            "description": "Memory usage in MB",
            "example": 125.67,
            "format": "double",
            "type": "number"
          },
          "misses": {
            "description": "Total cache misses",
            "example": 350,
            "type": "integer"
          },
          "newestEntryAge": {
            "description": "Age of newest entry in milliseconds",
            "example": 5000,
            "type": "integer"
          },
          "newestEntryAgeSeconds": {
            "description": "Age of newest entry in seconds",
            "example": 5,
            "type": "integer"
          },
          "oldestEntryAge": {
            "description": "Age of oldest entry in milliseconds",
            "example": 1800000,
            "type": "integer"
          },
          "oldestEntryAgeMinutes": {
            "description": "Age of oldest entry in minutes",
            "example": 30,
            "type": "integer"
          },
          "totalEntries": {
            "description": "Total entries in cache",
            "example": 450,
            "type": "integer"
          }
        },
        "required": [
          "hits",
          "misses",
          "hitRate",
          "hitRatePercent",
          "totalEntries",
          "memoryUsageMB",
          "memoryUsage",
          "oldestEntryAgeMinutes",
          "newestEntryAgeSeconds"
        ],
        "type": "object"
      },
      "CacheStatsResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/CacheStats"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "CachedAnalysisResult": {
        "description": "Cached AI analysis result",
        "properties": {
          "accountCode": {
            "description": "Suggested account code",
            "example": "403",
            "nullable": true,
            "type": "string"
          },
          "accountName": {
            "description": "Suggested account name",
            "example": "受取利息",
            "nullable": true,
            "type": "string"
          },
          "analysisType": {
            "$ref": "#/components/schemas/AIAnalysisType"
          },
          "bankTransactionId": {
            "description": "Bank transaction this analysis is for",
            "format": "uuid",
            "type": "string"
          },
          "category": {
            "description": "Categorization result",
            "example": "受取利息",
            "nullable": true,
            "type": "string"
          },
          "confidence": {
            "description": "AI confidence score (0.0-1.0)",
            "example": 0.95,
            "nullable": true,
            "type": "number"
          },
          "createdAt": {
            "description": "When analysis was created",
            "format": "date-time",
            "type": "string"
          },
          "entryType": {
            "description": "Journal entry type",
            "example": "interest_income",
            "nullable": true,
            "type": "string"
          },
          "expiresAt": {
            "description": "When analysis expires (TTL)",
            "format": "date-time",
            "type": "string"
          },
          "id": {
            "description": "Unique analysis ID",
            "format": "uuid",
            "type": "string"
          },
          "interestCalculation": {
            "$ref": "#/components/schemas/InterestIncomeCalculation",
            "nullable": true
          },
          "isCached": {
            "description": "Always true for cached results",
            "example": true,
            "type": "boolean"
          },
          "isExpired": {
            "description": "Whether analysis is past its TTL",
            "example": false,
            "type": "boolean"
          },
          "journalEntries": {
            "description": "Journal entry lines (for journal_entry type)",
            "items": {
              "properties": {
                "accountCode": {
                  "example": "102",
                  "type": "string"
                },
                "accountName": {
                  "example": "普通預金",
                  "type": "string"
                },
                "credit": {
                  "example": 0,
                  "type": "number"
                },
                "debit": {
                  "example": 851,
                  "type": "number"
                },
                "description": {
                  "type": "string"
                }
              },
              "type": "object"
            },
            "nullable": true,
            "type": "array"
          },
          "modelUsed": {
            "description": "AI model used for analysis",
            "example": "gpt-4o-mini",
            "nullable": true,
            "type": "string"
          },
          "reasoning": {
            "description": "AI reasoning for the suggestion",
            "nullable": true,
            "type": "string"
          },
          "status": {
            "$ref": "#/components/schemas/AIAnalysisStatus"
          },
          "version": {
            "description": "Version number (increments on model/prompt changes)",
            "example": 1,
            "type": "integer"
          }
        },
        "type": "object"
      },
      "CalculationMethodReference": {
        "properties": {
          "cons": {
            "description": "Disadvantages of this method",
            "example": [
              "実際の仕入が多くても控除できない",
              "2年間の継続適用"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "description": {
            "description": "Method description",
            "example": "業種別のみなし仕入率を適用する方法",
            "type": "string"
          },
          "label": {
            "description": "Method label in Japanese",
            "example": "簡易課税",
            "type": "string"
          },
          "pros": {
            "description": "Advantages of this method",
            "example": [
              "帳簿管理が簡単",
              "仕入が少ない業種で有利"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "requirements": {
            "description": "Requirements for using this method",
            "example": "基準期間の課税売上高5,000万円以下、事前届出",
            "type": "string"
          },
          "value": {
            "description": "Calculation method value",
            "example": "simplified",
            "type": "string"
          }
        },
        "required": [
          "value",
          "label",
          "description",
          "requirements",
          "pros",
          "cons"
        ],
        "type": "object"
      },
      "CalculationMethodReferenceResponse": {
        "properties": {
          "data": {
            "properties": {
              "methods": {
                "items": {
                  "$ref": "#/components/schemas/CalculationMethodReference"
                },
                "type": "array"
              }
            },
            "type": "object"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "CanonicalFinding": {
        "properties": {
          "checkRule": {
            "$ref": "#/components/schemas/IssueCode"
          },
          "confidence": {
            "description": "確信度 (任意)",
            "type": "number"
          },
          "cta": {
            "nullable": true,
            "properties": {
              "href": {
                "type": "string"
              },
              "kind": {
                "type": "string"
              },
              "label": {
                "type": "string"
              }
            },
            "type": "object"
          },
          "detail": {
            "description": "詳細説明 (任意)",
            "nullable": true,
            "type": "string"
          },
          "detectedAt": {
            "description": "検出日時",
            "format": "date-time",
            "type": "string"
          },
          "id": {
            "description": "指摘ID (engine:type:index形式)",
            "type": "string"
          },
          "legalBasis": {
            "description": "根拠法令 (任意)",
            "type": "string"
          },
          "log": {
            "description": "対応履歴",
            "items": {
              "properties": {
                "action": {
                  "type": "string"
                },
                "at": {
                  "description": "ISO 8601 timestamp",
                  "type": "string"
                },
                "note": {
                  "type": "string"
                }
              },
              "required": [
                "at",
                "action"
              ],
              "type": "object"
            },
            "type": "array"
          },
          "objectRefs": {
            "description": "指摘の対象オブジェクト (仕訳・取引・書類など)",
            "items": {
              "properties": {
                "id": {
                  "type": "string"
                },
                "kind": {
                  "type": "string"
                },
                "label": {
                  "nullable": true,
                  "type": "string"
                }
              },
              "required": [
                "kind",
                "id"
              ],
              "type": "object"
            },
            "type": "array"
          },
          "relatedNodes": {
            "description": "関連する計算書データフローのノードID (任意)",
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "resolvedAt": {
            "description": "解消日時",
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "scope": {
            "description": "適用スコープ (例: \"2026年度\", \"2026年6月\")",
            "type": "string"
          },
          "severity": {
            "description": "深刻度",
            "enum": [
              "blocker",
              "warning",
              "info"
            ],
            "type": "string"
          },
          "sourceEngine": {
            "description": "生成元エンジン",
            "enum": [
              "pre_filing_review",
              "integrity_check",
              "month_end",
              "financial_advisory"
            ],
            "type": "string"
          },
          "status": {
            "description": "対応状況",
            "enum": [
              "open",
              "in_progress",
              "resolved",
              "dismissed",
              "not_applicable"
            ],
            "type": "string"
          },
          "title": {
            "description": "短いタイトル (UI見出し用)",
            "type": "string"
          }
        },
        "required": [
          "id",
          "checkRule",
          "severity",
          "status",
          "title",
          "scope",
          "sourceEngine",
          "objectRefs",
          "detectedAt",
          "log"
        ],
        "type": "object"
      },
      "CashFlowForecast": {
        "properties": {
          "alerts": {
            "items": {
              "properties": {
                "date": {
                  "type": "string"
                },
                "message": {
                  "type": "string"
                },
                "severity": {
                  "enum": [
                    "warning",
                    "critical"
                  ],
                  "type": "string"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "bankBalance": {
            "description": "Latest bank balance of the company accounts",
            "type": "number"
          },
          "currentBalance": {
            "description": "Journal-derived 現預金 (GL 101 + 102), display only",
            "type": "number"
          },
          "events": {
            "items": {
              "$ref": "#/components/schemas/CashForecastEvent"
            },
            "type": "array"
          },
          "inflows": {
            "description": "Known inflow events (legacy shape)",
            "items": {
              "properties": {
                "amount": {
                  "type": "number"
                },
                "confidence": {
                  "enum": [
                    "high",
                    "medium",
                    "low"
                  ],
                  "type": "string"
                },
                "date": {
                  "type": "string"
                },
                "source": {
                  "type": "string"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "outflows": {
            "description": "Known outflow events (legacy shape)",
            "items": {
              "properties": {
                "amount": {
                  "type": "number"
                },
                "category": {
                  "type": "string"
                },
                "date": {
                  "type": "string"
                },
                "isRecurring": {
                  "type": "boolean"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "periodEnd": {
            "format": "date",
            "type": "string"
          },
          "periodStart": {
            "format": "date",
            "type": "string"
          },
          "projectedBalance": {
            "type": "number"
          },
          "scenario": {
            "description": "BL-975 what-if echo; null for the stored schedule (the baseline).",
            "nullable": true,
            "properties": {
              "officerCompFrom": {
                "example": "2027-02-16",
                "format": "date",
                "type": "string"
              },
              "officerCompMonthly": {
                "example": 0,
                "type": "integer"
              },
              "replacedEventCount": {
                "description": "役員報酬 events in the window repriced or dropped",
                "type": "integer"
              }
            },
            "required": [
              "officerCompMonthly",
              "officerCompFrom",
              "replacedEventCount"
            ],
            "type": "object"
          },
          "startingBalance": {
            "description": "The balance the weeks start from; null when no bank balance is on file (no risk is projected)",
            "nullable": true,
            "type": "number"
          },
          "startingBalanceAsOf": {
            "description": "YYYYMMDD of the latest bank row",
            "example": 20260925,
            "nullable": true,
            "type": "integer"
          },
          "startingBalanceSource": {
            "enum": [
              "company_accounts",
              "unassigned_pool",
              "last_non_zero",
              "none"
            ],
            "type": "string"
          },
          "unknownAmountCount": {
            "description": "Events with amount null (金額未確定)",
            "type": "integer"
          },
          "weeklyProjections": {
            "items": {
              "$ref": "#/components/schemas/CashForecastWeek"
            },
            "type": "array"
          }
        },
        "required": [
          "periodStart",
          "periodEnd",
          "currentBalance",
          "bankBalance",
          "startingBalance",
          "startingBalanceSource",
          "startingBalanceAsOf",
          "projectedBalance",
          "inflows",
          "outflows",
          "weeklyProjections",
          "events",
          "unknownAmountCount",
          "scenario",
          "alerts"
        ],
        "type": "object"
      },
      "CashForecastEvent": {
        "description": "One dated cash event behind the 資金繰り forecast (BL-052). Amounts come only from a record; null = 金額未確定.",
        "properties": {
          "amount": {
            "description": "Positive yen; null when no record states it",
            "nullable": true,
            "type": "number"
          },
          "amountSource": {
            "description": "The record the amount came from, when it differs from source",
            "nullable": true,
            "properties": {
              "id": {
                "type": "string"
              },
              "table": {
                "example": "tax_return_sessions",
                "type": "string"
              }
            },
            "required": [
              "table",
              "id"
            ],
            "type": "object"
          },
          "countsInBalance": {
            "description": "False when the amount is shown but kept out of every week and balance (a 消費税 refund: 入金日 unknown)",
            "type": "boolean"
          },
          "date": {
            "example": "2026-10-25",
            "format": "date",
            "type": "string"
          },
          "direction": {
            "enum": [
              "in",
              "out"
            ],
            "type": "string"
          },
          "id": {
            "description": "Stable key: source table, id and date",
            "type": "string"
          },
          "kind": {
            "enum": [
              "receivable",
              "payable",
              "tax",
              "payroll",
              "social_insurance",
              "agreement"
            ],
            "type": "string"
          },
          "label": {
            "example": "役員報酬（代表・10月分）",
            "type": "string"
          },
          "note": {
            "description": "How the date and amount were read (Japanese)",
            "nullable": true,
            "type": "string"
          },
          "source": {
            "properties": {
              "id": {
                "type": "string"
              },
              "table": {
                "example": "officer_compensation_schedule",
                "type": "string"
              }
            },
            "required": [
              "table",
              "id"
            ],
            "type": "object"
          }
        },
        "required": [
          "id",
          "date",
          "kind",
          "direction",
          "label",
          "amount",
          "countsInBalance",
          "note",
          "source",
          "amountSource"
        ],
        "type": "object"
      },
      "CashForecastWeek": {
        "properties": {
          "endBalance": {
            "type": "number"
          },
          "inflow": {
            "type": "number"
          },
          "netChange": {
            "type": "number"
          },
          "outflow": {
            "type": "number"
          },
          "riskLevel": {
            "enum": [
              "safe",
              "caution",
              "danger"
            ],
            "type": "string"
          },
          "startBalance": {
            "type": "number"
          },
          "unknownAmountCount": {
            "description": "Events this week with no stated amount — the week may be worse than shown",
            "type": "integer"
          },
          "week": {
            "example": "Week 1",
            "type": "string"
          },
          "weekEnd": {
            "format": "date",
            "type": "string"
          },
          "weekStart": {
            "format": "date",
            "type": "string"
          }
        },
        "required": [
          "week",
          "weekStart",
          "weekEnd",
          "startBalance",
          "endBalance",
          "netChange",
          "inflow",
          "outflow",
          "unknownAmountCount",
          "riskLevel"
        ],
        "type": "object"
      },
      "CategorizationResult": {
        "example": {
          "alternatives": [
            {
              "category": 15,
              "categoryName": "燃料費",
              "confidence": 0.4
            }
          ],
          "amountWarning": null,
          "categoryName": "旅費交通費",
          "confidence": 0.95,
          "matchedPattern": "nexco",
          "matchedRuleId": "uuid-...",
          "source": "vendor_rule",
          "suggestedCategory": 3
        },
        "properties": {
          "alternatives": {
            "items": {
              "properties": {
                "category": {
                  "type": "integer"
                },
                "categoryName": {
                  "type": "string"
                },
                "confidence": {
                  "type": "number"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "amountWarning": {
            "description": "Warning about amount threshold",
            "nullable": true,
            "type": "string"
          },
          "categoryName": {
            "type": "string"
          },
          "confidence": {
            "maximum": 1,
            "minimum": 0,
            "type": "number"
          },
          "matchedPattern": {
            "nullable": true,
            "type": "string"
          },
          "matchedRule": {
            "description": "The rule that matched, so the wizard card can name it and link to fix it.",
            "nullable": true,
            "properties": {
              "category": {
                "example": 3,
                "type": "integer"
              },
              "pattern": {
                "example": "GO",
                "type": "string"
              },
              "priority": {
                "example": 80,
                "type": "integer"
              },
              "ruleId": {
                "format": "uuid",
                "type": "string"
              },
              "ruleType": {
                "enum": [
                  "vendor",
                  "keyword",
                  "combined"
                ],
                "type": "string"
              },
              "scope": {
                "enum": [
                  "system",
                  "user"
                ],
                "type": "string"
              }
            },
            "type": "object"
          },
          "matchedRuleId": {
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "source": {
            "$ref": "#/components/schemas/SuggestionSource"
          },
          "suggestedCategory": {
            "maximum": 26,
            "minimum": 0,
            "type": "integer"
          }
        },
        "type": "object"
      },
      "CategorizeRequest": {
        "example": {
          "amount": 8500,
          "date": "2026-01-25",
          "description": "高速道路料金 東京IC-名古屋IC",
          "vendor": "NEXCO中日本"
        },
        "properties": {
          "amount": {
            "description": "Amount in JPY",
            "minimum": 0,
            "type": "number"
          },
          "date": {
            "description": "Transaction date",
            "format": "date",
            "type": "string"
          },
          "description": {
            "description": "Transaction description",
            "maxLength": 2000,
            "type": "string"
          },
          "vendor": {
            "description": "Vendor/merchant name",
            "maxLength": 500,
            "type": "string"
          }
        },
        "type": "object"
      },
      "CategorizeTransactionApiResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/CategorizeTransactionResponse"
          },
          "message": {
            "example": "Transaction categorized successfully",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "CategorizeTransactionRequest": {
        "properties": {
          "context": {
            "$ref": "#/components/schemas/CompanyContext"
          },
          "transaction": {
            "$ref": "#/components/schemas/TransactionInput"
          }
        },
        "required": [
          "transaction"
        ],
        "type": "object"
      },
      "CategorizeTransactionResponse": {
        "properties": {
          "decisionSource": {
            "description": "Who produced the answer: rule (deterministic, no AI), history (the tenant own decisive booking history, no AI), jev (Jev decision model, BE ADR-0013), llm (the chat model of the user)",
            "enum": [
              "rule",
              "history",
              "jev",
              "llm"
            ],
            "example": "history",
            "type": "string"
          },
          "interestCalculation": {
            "$ref": "#/components/schemas/InterestIncomeCalculation",
            "description": "v4.30: Interest income calculation (only present for bank interest transactions)"
          },
          "reasoning": {
            "description": "AI reasoning for categorization",
            "example": "Amazonからの購入で「オフィス用品」というキーワードから消耗品費として分類しました",
            "type": "string"
          },
          "suggestedAccounts": {
            "description": "List of suggested accounts",
            "items": {
              "$ref": "#/components/schemas/SuggestedAccount"
            },
            "type": "array"
          },
          "suggestedCategory": {
            "properties": {
              "confidence": {
                "description": "Confidence score",
                "example": 0.92,
                "format": "double",
                "maximum": 1,
                "minimum": 0,
                "type": "number"
              },
              "primary": {
                "description": "Primary category",
                "example": "消耗品費",
                "type": "string"
              },
              "secondary": {
                "description": "Secondary category",
                "example": "オフィス用品",
                "type": "string"
              }
            },
            "type": "object"
          },
          "taxCategory": {
            "description": "Tax category classification",
            "example": "課税仕入",
            "type": "string"
          },
          "transactionType": {
            "description": "Classified transaction type",
            "example": "事業費",
            "type": "string"
          }
        },
        "required": [
          "suggestedCategory",
          "suggestedAccounts",
          "transactionType",
          "taxCategory",
          "reasoning"
        ],
        "type": "object"
      },
      "CategoryRule": {
        "properties": {
          "baseConfidence": {
            "maximum": 0.98,
            "minimum": 0.3,
            "type": "number"
          },
          "categoryName": {
            "description": "Japanese category name",
            "type": "string"
          },
          "createdAt": {
            "format": "date-time",
            "type": "string"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "isActive": {
            "type": "boolean"
          },
          "isSystem": {
            "description": "true for built-in rules, false for user rules",
            "type": "boolean"
          },
          "lastMatchedAt": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "matchCount": {
            "description": "Number of times this rule has matched",
            "type": "integer"
          },
          "matchPattern": {
            "description": "Pattern to match (case-insensitive)",
            "type": "string"
          },
          "priority": {
            "maximum": 100,
            "minimum": 1,
            "type": "integer"
          },
          "ruleDescription": {
            "nullable": true,
            "type": "string"
          },
          "ruleName": {
            "nullable": true,
            "type": "string"
          },
          "ruleType": {
            "$ref": "#/components/schemas/CategoryRuleType"
          },
          "secondaryPattern": {
            "description": "Secondary pattern for combined rules",
            "nullable": true,
            "type": "string"
          },
          "suggestedCategory": {
            "maximum": 26,
            "minimum": 0,
            "type": "integer"
          },
          "updatedAt": {
            "format": "date-time",
            "type": "string"
          },
          "userCorrectionCount": {
            "description": "Times users changed this suggestion",
            "type": "integer"
          }
        },
        "type": "object"
      },
      "CategoryRuleType": {
        "description": "Rule matching type",
        "enum": [
          "vendor",
          "keyword",
          "combined"
        ],
        "type": "string"
      },
      "ChangelogChanges": {
        "properties": {
          "breaking": {
            "description": "Breaking changes",
            "items": {
              "$ref": "#/components/schemas/GitCommit"
            },
            "type": "array"
          },
          "chore": {
            "description": "Maintenance and chore tasks",
            "items": {
              "$ref": "#/components/schemas/GitCommit"
            },
            "type": "array"
          },
          "docs": {
            "description": "Documentation changes",
            "items": {
              "$ref": "#/components/schemas/GitCommit"
            },
            "type": "array"
          },
          "features": {
            "description": "New features and enhancements",
            "items": {
              "$ref": "#/components/schemas/GitCommit"
            },
            "type": "array"
          },
          "fixes": {
            "description": "Bug fixes and patches",
            "items": {
              "$ref": "#/components/schemas/GitCommit"
            },
            "type": "array"
          },
          "other": {
            "description": "Other changes",
            "items": {
              "$ref": "#/components/schemas/GitCommit"
            },
            "type": "array"
          },
          "perf": {
            "description": "Performance improvements",
            "items": {
              "$ref": "#/components/schemas/GitCommit"
            },
            "type": "array"
          },
          "refactor": {
            "description": "Code refactoring",
            "items": {
              "$ref": "#/components/schemas/GitCommit"
            },
            "type": "array"
          }
        },
        "required": [
          "features",
          "fixes",
          "docs",
          "perf",
          "refactor",
          "chore",
          "breaking",
          "other"
        ],
        "type": "object"
      },
      "ChangelogData": {
        "properties": {
          "stats": {
            "$ref": "#/components/schemas/ChangelogStats"
          },
          "versions": {
            "description": "Version history with changes",
            "items": {
              "$ref": "#/components/schemas/ChangelogVersion"
            },
            "type": "array"
          }
        },
        "required": [
          "versions",
          "stats"
        ],
        "type": "object"
      },
      "ChangelogResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/ChangelogData"
          },
          "message": {
            "example": "Changelog retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ChangelogStats": {
        "properties": {
          "lastUpdated": {
            "description": "Last update timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "totalCommits": {
            "description": "Total number of commits",
            "example": 150,
            "type": "number"
          },
          "totalVersions": {
            "description": "Total number of versions",
            "example": 5,
            "type": "number"
          }
        },
        "required": [
          "totalCommits",
          "totalVersions",
          "lastUpdated"
        ],
        "type": "object"
      },
      "ChangelogVersion": {
        "properties": {
          "changes": {
            "$ref": "#/components/schemas/ChangelogChanges"
          },
          "date": {
            "description": "Version release date",
            "example": "2024-01-15",
            "format": "date",
            "type": "string"
          },
          "tag": {
            "description": "Version tag",
            "enum": [
              "latest",
              "stable",
              "beta",
              "alpha"
            ],
            "example": "latest",
            "type": "string"
          },
          "version": {
            "description": "Version number",
            "example": "v1.2.3",
            "type": "string"
          }
        },
        "required": [
          "version",
          "date",
          "tag",
          "changes"
        ],
        "type": "object"
      },
      "CheckSummary": {
        "properties": {
          "errors": {
            "description": "Number of error-level violations",
            "example": 2,
            "type": "integer"
          },
          "infos": {
            "description": "Number of info-level violations",
            "example": 0,
            "type": "integer"
          },
          "passedChecks": {
            "description": "Number of checks that passed",
            "example": 12,
            "type": "integer"
          },
          "totalChecks": {
            "description": "Total number of checks performed",
            "example": 15,
            "type": "integer"
          },
          "warnings": {
            "description": "Number of warning-level violations",
            "example": 1,
            "type": "integer"
          }
        },
        "required": [
          "totalChecks",
          "passedChecks",
          "errors",
          "warnings",
          "infos"
        ],
        "type": "object"
      },
      "CircuitBreakerHealth": {
        "properties": {
          "failures": {
            "description": "Current failure count",
            "example": 0,
            "type": "number"
          },
          "lastFailure": {
            "description": "Timestamp of last failure",
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "name": {
            "description": "Service name",
            "example": "OpenAI",
            "type": "string"
          },
          "state": {
            "description": "Circuit state (CLOSED = healthy, OPEN = failing, HALF_OPEN = recovering)",
            "enum": [
              "CLOSED",
              "OPEN",
              "HALF_OPEN"
            ],
            "example": "CLOSED",
            "type": "string"
          }
        },
        "type": "object"
      },
      "ClaimsDocumentSummary": {
        "properties": {
          "attachmentCount": {
            "description": "Number of attached supporting documents",
            "example": 12,
            "type": "integer"
          },
          "currency": {
            "description": "Currency code",
            "example": "JPY",
            "type": "string"
          },
          "expenseCount": {
            "description": "Number of expenses in claims document",
            "example": 8,
            "type": "integer"
          },
          "hasInkan": {
            "$ref": "#/components/schemas/DockHasInkan"
          },
          "id": {
            "description": "Claims document identifier",
            "example": "456e7890-f12a-34b5-c678-901234567890",
            "format": "uuid",
            "type": "string"
          },
          "isLinkedToPayment": {
            "description": "Whether this claims document is linked to a payment document",
            "example": false,
            "type": "boolean"
          },
          "isLinkedToTravel": {
            "description": "Whether this claims document is linked to a travel report",
            "example": true,
            "type": "boolean"
          },
          "name": {
            "description": "Claims document name",
            "example": "2024年1月経費精算書 - 営業部",
            "type": "string"
          },
          "status": {
            "description": "Document status",
            "enum": [
              "draft",
              "published",
              "archived"
            ],
            "example": "published",
            "type": "string"
          },
          "totalAmount": {
            "description": "Total claims amount",
            "example": 45000,
            "type": "number"
          },
          "type": {
            "description": "Document type (claims)",
            "example": "claims",
            "type": "string"
          }
        },
        "required": [
          "id",
          "name",
          "type",
          "totalAmount",
          "currency",
          "status",
          "expenseCount",
          "attachmentCount",
          "isLinkedToTravel",
          "isLinkedToPayment"
        ],
        "type": "object"
      },
      "ClarifyingContext": {
        "description": "Context from a previous clarification prompt (v5.15). Sent when user selects a clarification suggestion.",
        "properties": {
          "clarification": {
            "description": "The clarification option the user selected",
            "example": "個人事業主としての税金の種類について知りたいですか？",
            "maxLength": 2000,
            "type": "string"
          },
          "original_question": {
            "description": "The original ambiguous question that triggered clarification",
            "example": "税金",
            "maxLength": 2000,
            "type": "string"
          }
        },
        "required": [
          "original_question",
          "clarification"
        ],
        "type": "object"
      },
      "ClassifyIntakeRequest": {
        "properties": {
          "blue_return": {
            "type": "boolean"
          },
          "duties": {
            "items": {
              "properties": {
                "is_managerial": {
                  "type": "boolean"
                },
                "label": {
                  "type": "string"
                },
                "tag": {
                  "type": "string"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "entity_type": {
            "enum": [
              "kk",
              "gk",
              "sole_prop"
            ],
            "type": "string"
          },
          "owner_annual_income_yen": {
            "description": "JPY integer",
            "type": "integer"
          },
          "proposed_annual_salary_yen": {
            "description": "JPY integer",
            "type": "integer"
          },
          "relation": {
            "enum": [
              "spouse",
              "child",
              "parent",
              "other"
            ],
            "type": "string"
          },
          "visa_category": {
            "enum": [
              "dependent",
              "spouse_of_japanese",
              "engineer_specialist",
              "skilled_labor",
              "business_manager",
              "permanent_resident",
              "special_permanent",
              "other_work_eligible"
            ],
            "nullable": true,
            "type": "string"
          }
        },
        "required": [
          "entity_type",
          "owner_annual_income_yen",
          "relation",
          "proposed_annual_salary_yen"
        ],
        "type": "object"
      },
      "ClassifyJournalRequest": {
        "properties": {
          "bankLine": {
            "example": "ﾅｲｾﾝﾄﾞｵﾌｲｽ045-XXXX -¥7,920",
            "maxLength": 200,
            "type": "string"
          }
        },
        "required": [
          "bankLine"
        ],
        "type": "object"
      },
      "ClassifyTransactionRequest": {
        "properties": {
          "amount": {
            "description": "Transaction amount (optional, for enhanced classification)",
            "example": 15000,
            "type": "number"
          },
          "description": {
            "description": "Transaction description to classify",
            "example": "Amazon Web Services 月額利用料",
            "type": "string"
          }
        },
        "required": [
          "description"
        ],
        "type": "object"
      },
      "ClassifyTransactionResponse": {
        "properties": {
          "data": {
            "properties": {
              "confidence": {
                "enum": [
                  "high",
                  "medium",
                  "low"
                ],
                "example": "high",
                "type": "string"
              },
              "matched": {
                "example": true,
                "type": "boolean"
              },
              "rule": {
                "nullable": true,
                "properties": {
                  "credit_account": {
                    "example": "普通預金",
                    "type": "string"
                  },
                  "credit_code": {
                    "example": "1120",
                    "type": "string"
                  },
                  "debit_account": {
                    "example": "通信費",
                    "type": "string"
                  },
                  "debit_code": {
                    "example": "6420",
                    "type": "string"
                  },
                  "keywords": {
                    "example": [
                      "AWS",
                      "Amazon Web Services"
                    ],
                    "items": {
                      "type": "string"
                    },
                    "type": "array"
                  },
                  "remark_template": {
                    "example": "クラウドサービス利用料",
                    "type": "string"
                  },
                  "tax_rate": {
                    "example": 0.1,
                    "type": "number"
                  }
                },
                "type": "object"
              },
              "suggestions": {
                "items": {
                  "properties": {
                    "credit_account": {
                      "type": "string"
                    },
                    "debit_account": {
                      "type": "string"
                    },
                    "reason": {
                      "type": "string"
                    }
                  },
                  "type": "object"
                },
                "type": "array"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "取引を分類しました",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "type": "object"
      },
      "ClearLogsResponse": {
        "properties": {
          "message": {
            "example": "Log buffer cleared",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message"
        ],
        "type": "object"
      },
      "ClientAICreationRequest": {
        "properties": {
          "text": {
            "description": "Free text to extract client details from (名刺, 請求書, email signature, …)",
            "example": "株式会社サンプル 営業部 山田太郎 TEL 03-1234-5678 登録番号 T1234567890123",
            "maxLength": 10000,
            "minLength": 1,
            "type": "string"
          }
        },
        "required": [
          "text"
        ],
        "type": "object"
      },
      "ClientDocument": {
        "description": "Document linked to a trading partner",
        "properties": {
          "amount": {
            "description": "Document total amount",
            "example": 110000,
            "nullable": true,
            "type": "number"
          },
          "amountMatchesDeposit": {
            "description": "Whether document amount matches linked deposit (±¥1)",
            "example": true,
            "nullable": true,
            "type": "boolean"
          },
          "amountSource": {
            "description": "Provenance of the resolved amount",
            "enum": [
              "summary_total",
              "summary_total_amount",
              "summary_reimbursement",
              "summary_subtotal_tax",
              "line_items_derived",
              "sales_invoice_table",
              "linked_deposit",
              "none"
            ],
            "example": "summary_total",
            "type": "string"
          },
          "createdAt": {
            "description": "Creation timestamp",
            "format": "date-time",
            "type": "string"
          },
          "documentName": {
            "description": "Document name",
            "example": "請求書_ABC株式会社_2026-01",
            "type": "string"
          },
          "documentType": {
            "description": "Document type",
            "enum": [
              "sales_quotation",
              "purchase_order",
              "delivery_note",
              "sales_invoice"
            ],
            "example": "sales_invoice",
            "type": "string"
          },
          "id": {
            "description": "Document ID",
            "format": "uuid",
            "type": "string"
          },
          "linkType": {
            "description": "How the document is linked to the client",
            "enum": [
              "direct",
              "client_info",
              "buyer_info",
              "supplier_info",
              "document_name",
              "unknown"
            ],
            "example": "client_info",
            "type": "string"
          },
          "linkedDepositAmount": {
            "description": "Bank deposit amount linked via document_transaction_links",
            "example": 550000,
            "nullable": true,
            "type": "number"
          },
          "linkedDepositDate": {
            "description": "Linked bank deposit date (YYYYMMDD)",
            "example": 20260430,
            "nullable": true,
            "type": "integer"
          },
          "needsReview": {
            "description": "True when link or amount provenance is inferred and should be verified",
            "example": false,
            "type": "boolean"
          },
          "status": {
            "description": "Document status",
            "example": "published",
            "type": "string"
          },
          "updatedAt": {
            "description": "Last update timestamp",
            "format": "date-time",
            "type": "string"
          }
        },
        "required": [
          "id",
          "documentName",
          "documentType",
          "status",
          "linkType",
          "amountSource",
          "needsReview",
          "createdAt",
          "updatedAt"
        ],
        "type": "object"
      },
      "ClientDocumentsResponse": {
        "properties": {
          "data": {
            "properties": {
              "items": {
                "items": {
                  "$ref": "#/components/schemas/ClientDocument"
                },
                "type": "array"
              },
              "pagination": {
                "properties": {
                  "currentPage": {
                    "example": 1,
                    "type": "number"
                  },
                  "hasNext": {
                    "example": true,
                    "type": "boolean"
                  },
                  "hasPrevious": {
                    "example": false,
                    "type": "boolean"
                  },
                  "pageSize": {
                    "example": 20,
                    "type": "number"
                  },
                  "totalItems": {
                    "example": 25,
                    "type": "number"
                  },
                  "totalPages": {
                    "example": 2,
                    "type": "number"
                  }
                },
                "type": "object"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Client documents retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ClientExportQuery": {
        "description": "Query parameters for client export",
        "properties": {
          "client_type": {
            "description": "Filter by client type (0=Customer/得意先, 1=Supplier/仕入先, 2=Both/両方). Omit for all types.",
            "enum": [
              0,
              1,
              2
            ],
            "type": "number"
          },
          "format": {
            "default": "csv",
            "description": "Export format",
            "enum": [
              "csv",
              "json"
            ],
            "type": "string"
          },
          "is_qualified": {
            "description": "Filter to only qualified invoice issuers (has registration_number)",
            "type": "boolean"
          },
          "search": {
            "description": "Search filter for name, furigana, corporate number, contact person, or email",
            "type": "string"
          }
        },
        "type": "object"
      },
      "ClientFullResponse": {
        "description": "Composite response for client detail page — client, stats, and documents in one call (v5.15)",
        "properties": {
          "data": {
            "allOf": [
              {
                "$ref": "#/components/schemas/ClientResponse"
              },
              {
                "properties": {
                  "documents": {
                    "description": "Recent documents associated with this client",
                    "nullable": true,
                    "properties": {
                      "items": {
                        "items": {
                          "type": "object"
                        },
                        "type": "array"
                      },
                      "pagination": {
                        "properties": {
                          "currentPage": {
                            "example": 1,
                            "type": "integer"
                          },
                          "pageSize": {
                            "example": 10,
                            "type": "integer"
                          },
                          "totalItems": {
                            "example": 15,
                            "type": "integer"
                          },
                          "totalPages": {
                            "example": 2,
                            "type": "integer"
                          }
                        },
                        "type": "object"
                      }
                    },
                    "type": "object"
                  },
                  "stats": {
                    "description": "Client usage statistics (document counts, invoice totals, etc.)",
                    "nullable": true,
                    "properties": {
                      "documentCount": {
                        "example": 15,
                        "type": "integer"
                      },
                      "invoiceTotal": {
                        "example": 1500000,
                        "type": "integer"
                      },
                      "lastActivityDate": {
                        "format": "date-time",
                        "type": "string"
                      }
                    },
                    "type": "object"
                  }
                },
                "type": "object"
              }
            ],
            "description": "Client data merged with optional stats and documents",
            "type": "object"
          },
          "meta": {
            "properties": {
              "cached": {
                "type": "boolean"
              },
              "durationMs": {
                "example": 120,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "type": "object"
      },
      "ClientListResponse": {
        "properties": {
          "data": {
            "properties": {
              "items": {
                "items": {
                  "$ref": "#/components/schemas/ClientResponse"
                },
                "type": "array"
              },
              "pagination": {
                "properties": {
                  "currentPage": {
                    "example": 1,
                    "type": "number"
                  },
                  "hasNext": {
                    "example": true,
                    "type": "boolean"
                  },
                  "hasPrevious": {
                    "example": false,
                    "type": "boolean"
                  },
                  "pageSize": {
                    "example": 10,
                    "type": "number"
                  },
                  "totalItems": {
                    "example": 25,
                    "type": "number"
                  },
                  "totalPages": {
                    "example": 3,
                    "type": "number"
                  }
                },
                "required": [
                  "currentPage",
                  "pageSize",
                  "totalItems",
                  "totalPages",
                  "hasNext",
                  "hasPrevious"
                ],
                "type": "object"
              }
            },
            "required": [
              "items",
              "pagination"
            ],
            "type": "object"
          },
          "message": {
            "example": "Clients retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ClientQuery": {
        "properties": {
          "page_number": {
            "description": "Page number for pagination (starts from 1)",
            "example": 1,
            "minimum": 1,
            "type": "number"
          },
          "page_size": {
            "description": "Number of items per page",
            "example": 10,
            "maximum": 100,
            "minimum": 1,
            "type": "number"
          },
          "search": {
            "description": "Search term to filter clients by name, furigana, corporate number, contact person, or email",
            "example": "サンプル",
            "nullable": true,
            "type": "string"
          },
          "sort_by": {
            "description": "Field to sort by",
            "enum": [
              "name",
              "furigana",
              "corporate_number",
              "contact_person",
              "created_at",
              "updated_at"
            ],
            "example": "created_at",
            "nullable": true,
            "type": "string"
          },
          "sort_order": {
            "description": "Sort order",
            "enum": [
              "asc",
              "desc"
            ],
            "example": "desc",
            "nullable": true,
            "type": "string"
          }
        },
        "required": [
          "page_number",
          "page_size"
        ],
        "type": "object"
      },
      "ClientResponse": {
        "properties": {
          "address": {
            "description": "Company address",
            "example": "東京都渋谷区サンプル１丁目２番３号",
            "nullable": true,
            "type": "string"
          },
          "client_type": {
            "description": "Client type",
            "enum": [
              0,
              1,
              2
            ],
            "example": 0,
            "nullable": true,
            "type": "number"
          },
          "contact_person": {
            "description": "Primary contact person name",
            "example": "山田太郎",
            "type": "string"
          },
          "corporate_number": {
            "description": "Japanese corporate number",
            "example": "1234567890123",
            "nullable": true,
            "type": "string"
          },
          "created_at": {
            "description": "Client creation timestamp",
            "format": "date-time",
            "type": "string"
          },
          "created_by": {
            "description": "ID of user who created the client",
            "format": "uuid",
            "type": "string"
          },
          "deleted_at": {
            "description": "Deletion timestamp",
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "deleted_by": {
            "description": "ID of user who deleted the client",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "email": {
            "description": "Contact email address",
            "example": "contact@example.co.jp",
            "format": "email",
            "nullable": true,
            "type": "string"
          },
          "furigana": {
            "description": "Company name in katakana (furigana)",
            "example": "サンプルカブシキガイシャ",
            "nullable": true,
            "type": "string"
          },
          "id": {
            "description": "Unique client identifier",
            "format": "uuid",
            "type": "string"
          },
          "is_deleted": {
            "default": false,
            "description": "Soft delete flag",
            "type": "boolean"
          },
          "name": {
            "description": "Official client company name",
            "example": "サンプル株式会社",
            "type": "string"
          },
          "phone": {
            "description": "Contact phone number",
            "example": "03-0000-0000",
            "nullable": true,
            "type": "string"
          },
          "registration_number": {
            "description": "Invoice registration number with T prefix",
            "example": "T1234567890123",
            "nullable": true,
            "type": "string"
          },
          "updated_at": {
            "description": "Last update timestamp",
            "format": "date-time",
            "type": "string"
          },
          "updated_by": {
            "description": "ID of user who last updated the client",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          }
        },
        "required": [
          "id",
          "name",
          "corporate_number",
          "contact_person",
          "created_at",
          "updated_at",
          "created_by",
          "is_deleted"
        ],
        "type": "object"
      },
      "ClientStats": {
        "description": "Comprehensive trading partner statistics",
        "properties": {
          "deliveryNoteCount": {
            "description": "Total number of delivery notes (納品書) linked to this client",
            "example": 5,
            "type": "number"
          },
          "documentCount": {
            "description": "Total number of ALL documents linked to this client (all types)",
            "example": 33,
            "type": "number"
          },
          "documentsByType": {
            "description": "Document count breakdown by type",
            "items": {
              "properties": {
                "count": {
                  "example": 15,
                  "type": "number"
                },
                "type": {
                  "example": "sales_invoice",
                  "type": "string"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "invoiceCount": {
            "description": "Total number of invoices linked to this client",
            "example": 15,
            "type": "number"
          },
          "lastActivityDate": {
            "description": "Most recent document activity date",
            "example": "2026-01-10T10:30:00.000Z",
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "purchaseOrderCount": {
            "description": "Total number of purchase orders (発注書) linked to this client",
            "example": 5,
            "type": "number"
          },
          "quotationCount": {
            "description": "Total number of quotations linked to this client",
            "example": 8,
            "type": "number"
          },
          "totalInvoiceAmount": {
            "description": "Sum of all invoice amounts (税込)",
            "example": 1500000,
            "type": "number"
          },
          "totalQuotationAmount": {
            "description": "Sum of all quotation amounts (税込)",
            "example": 2000000,
            "type": "number"
          }
        },
        "required": [
          "invoiceCount",
          "quotationCount",
          "purchaseOrderCount",
          "deliveryNoteCount",
          "documentCount",
          "totalInvoiceAmount",
          "totalQuotationAmount",
          "lastActivityDate",
          "documentsByType"
        ],
        "type": "object"
      },
      "ClientStatsResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/ClientStats"
          },
          "message": {
            "example": "Client statistics retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ClientUsageApiKeySource": {
        "description": "Source of the API key used for the operation",
        "enum": [
          0,
          1
        ],
        "example": 0,
        "type": "integer",
        "x-enum-varnames": [
          "USER_KEY",
          "SYSTEM_KEY"
        ]
      },
      "ClientUsageOperationType": {
        "description": "Type of AI operation performed",
        "enum": [
          0,
          1,
          2,
          3,
          4,
          5,
          6
        ],
        "example": 0,
        "type": "integer",
        "x-enum-varnames": [
          "TEXT_GENERATION",
          "IMAGE_ANALYSIS",
          "PDF_ANALYSIS",
          "DOCX_ANALYSIS",
          "EMBEDDINGS",
          "WEB_SCRAPE",
          "WEB_SEARCH"
        ]
      },
      "ClientWithStats": {
        "allOf": [
          {
            "$ref": "#/components/schemas/ClientResponse"
          },
          {
            "properties": {
              "stats": {
                "nullable": true,
                "properties": {
                  "documentCount": {
                    "description": "Total of ALL document types",
                    "example": 33,
                    "type": "number"
                  },
                  "invoiceCount": {
                    "example": 15,
                    "type": "number"
                  },
                  "lastActivityDate": {
                    "format": "date-time",
                    "nullable": true,
                    "type": "string"
                  },
                  "needsReviewCount": {
                    "description": "Related documents with inferred link or amount provenance needing review",
                    "example": 1,
                    "type": "number"
                  },
                  "quotationCount": {
                    "example": 8,
                    "type": "number"
                  },
                  "totalAmount": {
                    "example": 3500000,
                    "type": "number"
                  }
                },
                "type": "object"
              }
            },
            "type": "object"
          }
        ]
      },
      "ClientsWithStatsResponse": {
        "properties": {
          "data": {
            "properties": {
              "items": {
                "items": {
                  "$ref": "#/components/schemas/ClientWithStats"
                },
                "type": "array"
              },
              "pagination": {
                "properties": {
                  "currentPage": {
                    "example": 1,
                    "type": "number"
                  },
                  "hasNext": {
                    "example": true,
                    "type": "boolean"
                  },
                  "hasPrevious": {
                    "example": false,
                    "type": "boolean"
                  },
                  "pageSize": {
                    "example": 10,
                    "type": "number"
                  },
                  "totalItems": {
                    "example": 25,
                    "type": "number"
                  },
                  "totalPages": {
                    "example": 3,
                    "type": "number"
                  }
                },
                "type": "object"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Clients with stats retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "CommitsResponse": {
        "properties": {
          "data": {
            "description": "Git commits",
            "items": {
              "$ref": "#/components/schemas/GitCommit"
            },
            "type": "array"
          },
          "message": {
            "example": "Git commits retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "CompaniesProgressResponse": {
        "properties": {
          "data": {
            "items": {
              "$ref": "#/components/schemas/CompanyProgress"
            },
            "type": "array"
          },
          "success": {
            "example": true,
            "type": "boolean"
          },
          "timestamp": {
            "example": "2024-01-15T10:30:00Z",
            "format": "date-time",
            "type": "string"
          }
        },
        "required": [
          "success",
          "data",
          "timestamp"
        ],
        "type": "object"
      },
      "Company": {
        "properties": {
          "address2": {
            "description": "Secondary address line (建物名・階数等) - building name, floor, etc.",
            "example": "サクラビル5F",
            "maxLength": 255,
            "nullable": true,
            "type": "string"
          },
          "business_objectives": {
            "description": "Business objectives (事業目的/目的) array. Extracted from 定款 article4.objectives. Used for tax deduction validation.",
            "example": [
              "ソフトウェアの開発・販売",
              "ITコンサルティング業",
              "Webサイトの企画、制作、運営"
            ],
            "items": {
              "type": "string"
            },
            "nullable": true,
            "type": "array"
          },
          "capital": {
            "description": "Company capital in Japanese Yen",
            "example": 1000000,
            "format": "decimal",
            "minimum": 0,
            "nullable": true,
            "type": "number"
          },
          "corporate_number": {
            "description": "Japanese corporate number (法人番号) - 13 digits",
            "example": "1234567890123",
            "maxLength": 13,
            "minLength": 13,
            "nullable": true,
            "pattern": "^[0-9]{13}$",
            "type": "string"
          },
          "created_at": {
            "description": "Creation timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "current_fiscal_year_end": {
            "description": "Read only: end (YYYYMMDD) of the 事業年度 containing today.",
            "nullable": true,
            "type": "integer"
          },
          "current_fiscal_year_start": {
            "description": "Read only: start (YYYYMMDD) of the 事業年度 containing today (JST) — a fiscal_periods ANNUAL row when one exists, else the stored config rolled forward by whole years.",
            "nullable": true,
            "type": "integer"
          },
          "deleted_at": {
            "description": "Deletion timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "executive_compensation": {
            "description": "Monthly executive compensation (役員報酬) in yen. Extracted from 定款 article17 (e.g., \"月額２０万円\" → 200000).",
            "example": 200000,
            "nullable": true,
            "type": "integer"
          },
          "first_fiscal_year_end": {
            "description": "First fiscal year end (最初の事業年度末) in YYYYMMDD format. Extracted from 定款 article31. May differ from regular fiscal_year_end.",
            "example": 20260215,
            "nullable": true,
            "type": "integer"
          },
          "fiscal_year_end": {
            "description": "Fiscal year end date as stored (MMDD legacy, or YYYYMMDD of the incorporation period). Never advanced; the live period is current_fiscal_year_end.",
            "example": 331,
            "minimum": 101,
            "nullable": true,
            "type": "integer"
          },
          "fiscal_year_source": {
            "description": "Read only: where current_fiscal_year_* came from.",
            "enum": [
              "fiscal_periods",
              "rolled",
              "stored"
            ],
            "type": "string"
          },
          "fiscal_year_start": {
            "description": "Fiscal year start date in MMDD format",
            "example": 401,
            "maximum": 1231,
            "minimum": 101,
            "nullable": true,
            "type": "integer"
          },
          "id": {
            "description": "Company unique identifier",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "incorporation_date": {
            "description": "Company incorporation/establishment date (開業日) in YYYYMMDD format. Extracted from 定款 signature.date field.",
            "example": 20250606,
            "nullable": true,
            "type": "integer"
          },
          "invoice_registration_date": {
            "description": "Invoice registration date",
            "example": "2023-10-01T00:00:00.000Z",
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "invoice_registration_number": {
            "description": "Qualified invoice issuer registration number (適格請求書発行事業者登録番号)",
            "example": "T1234567890123",
            "maxLength": 14,
            "nullable": true,
            "pattern": "^T[0-9]{13}$",
            "type": "string"
          },
          "invoice_registration_verified": {
            "default": false,
            "description": "Whether invoice registration is verified",
            "example": true,
            "type": "boolean"
          },
          "invoice_registration_verified_at": {
            "description": "Invoice registration verification timestamp",
            "example": "2023-10-01T10:30:00.000Z",
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "is_deleted": {
            "default": false,
            "description": "Whether company is deleted (soft delete)",
            "example": false,
            "type": "boolean"
          },
          "is_multiple_workplace_employee": {
            "default": false,
            "description": "Multiple workplace employee flag (二以上事業所勤務者).\nWhen true: This company is a secondary workplace (従たる給与) → Uses 乙欄 tax table (higher rate).\nWhen false: This company is the primary workplace (主たる給与) → Uses 甲欄 tax table (standard rate).\n\nTax implications:\n- 甲欄 (Kou-ran): Lower withholding rate, eligible for 年末調整 (year-end adjustment) at this company\n- 乙欄 (Otsu-ran): Higher withholding rate, must file 確定申告 (final tax return) Feb 16 - Mar 15\n\nReference: NTA No.2520 - 2か所以上から給与をもらっている人の源泉徴収\nhttps://www.nta.go.jp/taxes/shiraberu/taxanswer/gensen/2520.htm",
            "example": false,
            "type": "boolean"
          },
          "is_qualified_invoice_issuer": {
            "default": false,
            "description": "Whether company is a qualified invoice issuer (適格請求書発行事業者)",
            "example": true,
            "type": "boolean"
          },
          "linked_document_id": {
            "description": "Linked Teikan document ID",
            "example": "456e7890-f12a-34b5-c678-901234567890",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "member_info": {
            "description": "Member/shareholder information (社員・出資情報). Extracted from 定款.",
            "nullable": true,
            "properties": {
              "members": {
                "items": {
                  "properties": {
                    "address": {
                      "example": "東京都渋谷区渋谷1-1-1",
                      "type": "string"
                    },
                    "capitalContribution": {
                      "example": 1000000,
                      "type": "number"
                    },
                    "name": {
                      "example": "田中太郎",
                      "type": "string"
                    }
                  },
                  "type": "object"
                },
                "type": "array"
              },
              "totalCapital": {
                "example": 1000000,
                "type": "number"
              }
            },
            "type": "object"
          },
          "name": {
            "description": "Company name in Japanese",
            "example": "株式会社ソロボス",
            "maxLength": 255,
            "type": "string"
          },
          "office_address": {
            "description": "Company office address in Japanese format",
            "example": "東京都渋谷区渋谷1-1-1",
            "maxLength": 255,
            "nullable": true,
            "type": "string"
          },
          "owner_id": {
            "description": "Company owner (user) identifier",
            "example": "abc12345-def6-7890-ghij-klmnopqrstuv",
            "format": "uuid",
            "type": "string"
          },
          "phone_number": {
            "description": "Company phone number (電話番号). Extracted from 経費規定 companyInfo.tel field.",
            "example": "070-8459-3512",
            "maxLength": 20,
            "nullable": true,
            "type": "string"
          },
          "postal_code": {
            "description": "Postal code (郵便番号) in Japanese format XXX-XXXX",
            "example": "100-0001",
            "maxLength": 10,
            "nullable": true,
            "type": "string"
          },
          "public_notice_method": {
            "description": "Public notice method (公告方法). Extracted from 定款 article3 (e.g., \"官報に掲載してする\").",
            "example": "官報に掲載してする",
            "nullable": true,
            "type": "string"
          },
          "representative": {
            "description": "Representative director name (代表取締役)",
            "example": "田中太郎",
            "maxLength": 255,
            "nullable": true,
            "type": "string"
          },
          "setup_completed": {
            "default": false,
            "description": "Whether company setup is completed",
            "example": true,
            "type": "boolean"
          },
          "social_insurance_multi_employer": {
            "description": "社会保険の二以上事業所勤務: the representative is also enrolled in 健康保険・厚生年金 at another company. null = not answered (the 算定基礎届 guidance then keeps its conditional wording). Not the income-tax 乙欄 flag.",
            "example": null,
            "nullable": true,
            "type": "boolean"
          },
          "updated_at": {
            "description": "Last update timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          }
        },
        "required": [
          "id",
          "owner_id",
          "name",
          "setup_completed",
          "invoice_registration_verified",
          "is_qualified_invoice_issuer",
          "is_multiple_workplace_employee",
          "is_deleted",
          "created_at",
          "updated_at"
        ],
        "type": "object"
      },
      "CompanyContext": {
        "properties": {
          "agreements": {
            "items": {
              "$ref": "#/components/schemas/CompanyContextAgreement"
            },
            "type": "array"
          },
          "engagements": {
            "items": {
              "$ref": "#/components/schemas/CompanyContextEngagement"
            },
            "type": "array"
          },
          "evidence": {
            "$ref": "#/components/schemas/CompanyContextEvidence"
          },
          "gaps": {
            "description": "まだ判明していない事項。呼び出し側がユーザーに確認してよいのはこの範囲のみ。ここに現れない項目は既知。",
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "generatedAt": {
            "format": "date-time",
            "type": "string"
          },
          "identity": {
            "$ref": "#/components/schemas/CompanyContextIdentity"
          },
          "openQuestions": {
            "items": {
              "$ref": "#/components/schemas/OpenQuestion"
            },
            "type": "array"
          },
          "provenance": {
            "items": {
              "$ref": "#/components/schemas/CompanyContextProvenance"
            },
            "type": "array"
          },
          "tax": {
            "$ref": "#/components/schemas/CompanyContextTax"
          },
          "topCounterparties": {
            "items": {
              "$ref": "#/components/schemas/CompanyContextCounterparty"
            },
            "type": "array"
          }
        },
        "required": [
          "generatedAt",
          "identity",
          "tax",
          "engagements",
          "agreements",
          "topCounterparties",
          "openQuestions",
          "evidence",
          "provenance",
          "gaps"
        ],
        "type": "object"
      },
      "CompanyContextAgreement": {
        "properties": {
          "autoRenew": {
            "nullable": true,
            "type": "boolean"
          },
          "counterpartyName": {
            "nullable": true,
            "type": "string"
          },
          "depositAmount": {
            "description": "敷金・保証金",
            "nullable": true,
            "type": "string"
          },
          "docClass": {
            "enum": [
              "contract",
              "lease",
              "loan_agreement",
              "employment_agreement",
              "insurance_policy"
            ],
            "type": "string"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "inForce": {
            "description": "本日が契約期間内か",
            "type": "boolean"
          },
          "isFixedTerm": {
            "description": "定期借家等、更新のない確定期間契約",
            "nullable": true,
            "type": "boolean"
          },
          "keyClauses": {
            "description": "条項ラベルのみ",
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "ourRole": {
            "enum": [
              "lessee",
              "lessor",
              "borrower",
              "lender",
              "client",
              "contractor",
              "employer",
              "employee",
              "insured"
            ],
            "nullable": true,
            "type": "string"
          },
          "recurringAmount": {
            "nullable": true,
            "type": "string"
          },
          "recurringPeriod": {
            "enum": [
              "monthly",
              "quarterly",
              "semiannual",
              "annual",
              "one_time"
            ],
            "nullable": true,
            "type": "string"
          },
          "recurringSurchargeAmount": {
            "description": "管理費・共益費等",
            "nullable": true,
            "type": "string"
          },
          "recurringSurchargeLabel": {
            "nullable": true,
            "type": "string"
          },
          "sourceFileId": {
            "format": "uuid",
            "type": "string"
          },
          "statedTaxAmount": {
            "description": "契約書に記載された消費税額（再計算値ではない）",
            "nullable": true,
            "type": "string"
          },
          "status": {
            "enum": [
              "draft",
              "confirmed",
              "superseded",
              "terminated"
            ],
            "type": "string"
          },
          "summaryJa": {
            "nullable": true,
            "type": "string"
          },
          "termEnd": {
            "format": "date",
            "nullable": true,
            "type": "string"
          },
          "termStart": {
            "format": "date",
            "nullable": true,
            "type": "string"
          },
          "title": {
            "type": "string"
          }
        },
        "type": "object"
      },
      "CompanyContextBriefing": {
        "additionalProperties": false,
        "description": "format=markdown の応答。LLMのシステムプロンプトに前置きする日本語ブリーフィング。",
        "properties": {
          "generatedAt": {
            "format": "date-time",
            "type": "string"
          },
          "markdown": {
            "type": "string"
          }
        },
        "required": [
          "markdown",
          "generatedAt"
        ],
        "type": "object"
      },
      "CompanyContextCounterparty": {
        "properties": {
          "documentCount": {
            "type": "integer"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "isProvisional": {
            "description": "書類から自動作成され、人の確認を経ていない",
            "type": "boolean"
          },
          "name": {
            "type": "string"
          },
          "registrationNumber": {
            "nullable": true,
            "type": "string"
          },
          "registrationStatus": {
            "enum": [
              "registered",
              "revoked",
              "expired",
              "not_found",
              "unverified"
            ],
            "type": "string"
          }
        },
        "type": "object"
      },
      "CompanyContextEngagement": {
        "description": "依頼中・契約中の専門家（税理士・監査人 等）の 5W1H。当社記入のメモで、申告には使わない。",
        "properties": {
          "displayName": {
            "type": "string"
          },
          "fiscalYear": {
            "description": "null = standing engagement (顧問契約)",
            "nullable": true,
            "type": "integer"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "officeName": {
            "nullable": true,
            "type": "string"
          },
          "professionalType": {
            "type": "string"
          },
          "status": {
            "type": "string"
          },
          "what": {
            "nullable": true,
            "type": "string"
          },
          "when": {
            "nullable": true,
            "type": "string"
          },
          "why": {
            "nullable": true,
            "type": "string"
          }
        },
        "required": [
          "id",
          "professionalType",
          "status",
          "displayName",
          "officeName",
          "fiscalYear",
          "why",
          "what",
          "when"
        ],
        "type": "object"
      },
      "CompanyContextEvidence": {
        "properties": {
          "byClass": {
            "items": {
              "properties": {
                "count": {
                  "type": "integer"
                },
                "docClass": {
                  "type": "string"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "classified": {
            "type": "integer"
          },
          "earliestTransactionDate": {
            "format": "date",
            "nullable": true,
            "type": "string"
          },
          "latestTransactionDate": {
            "format": "date",
            "nullable": true,
            "type": "string"
          },
          "missingSearchableFields": {
            "description": "電帳法検索要件（取引年月日・取引金額・取引先）のいずれかが欠落した書類数",
            "type": "integer"
          },
          "totalDocuments": {
            "type": "integer"
          },
          "unclassified": {
            "type": "integer"
          }
        },
        "type": "object"
      },
      "CompanyContextIdentity": {
        "properties": {
          "businessType": {
            "nullable": true,
            "type": "string"
          },
          "capital": {
            "description": "資本金（decimal as string）",
            "nullable": true,
            "type": "string"
          },
          "companyId": {
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "corporateNumber": {
            "example": "5011003021894",
            "nullable": true,
            "type": "string"
          },
          "entityType": {
            "example": "godo_kaisha",
            "nullable": true,
            "type": "string"
          },
          "incorporationDate": {
            "description": "設立日 (YYYYMMDD)",
            "example": 20250606,
            "nullable": true,
            "type": "integer"
          },
          "name": {
            "example": "ｋｅｎｓａｕｒｕｓ合同会社",
            "nullable": true,
            "type": "string"
          },
          "nameKana": {
            "nullable": true,
            "type": "string"
          },
          "officeAddress": {
            "nullable": true,
            "type": "string"
          },
          "representative": {
            "nullable": true,
            "type": "string"
          }
        },
        "type": "object"
      },
      "CompanyContextProvenance": {
        "description": "companies.metadata_sources の項目別出所。エントリがない項目は出所未記録。共通スキーマは src/utils/provenance.ts。",
        "properties": {
          "confidence": {
            "maximum": 1,
            "minimum": 0,
            "nullable": true,
            "type": "number"
          },
          "field": {
            "example": "fiscal_year_start",
            "type": "string"
          },
          "isHuman": {
            "description": "true の場合は人間が確定した値。自動処理で上書きしてはならない。",
            "type": "boolean"
          },
          "source": {
            "enum": [
              "manual",
              "user",
              "nta-corporate-api",
              "nta-invoice-api",
              "postal-code-api",
              "teikan-extract",
              "oss-extract",
              "document-extract",
              "extraction",
              "journal-inference",
              "period-inference",
              "heuristic",
              "backfill",
              "system-default",
              "carry-forward"
            ],
            "example": "teikan-extract",
            "type": "string"
          },
          "sourceAt": {
            "nullable": true,
            "type": "string"
          },
          "sourceLabel": {
            "description": "source の日本語表示名。FE はこの値をそのまま表示してよい。",
            "example": "定款から抽出",
            "type": "string"
          },
          "sourceRef": {
            "description": "値を検証するための参照先（ファイルID・法人番号・スナップショットID等）。",
            "example": "file:9a1c…",
            "nullable": true,
            "type": "string"
          }
        },
        "required": [
          "field",
          "source",
          "sourceLabel",
          "isHuman"
        ],
        "type": "object"
      },
      "CompanyContextTax": {
        "properties": {
          "consumptionTaxElectionFiled": {
            "description": "課税事業者選択届出書",
            "nullable": true,
            "type": "boolean"
          },
          "consumptionTaxPeriodShortening": {
            "description": "課税期間特例",
            "enum": [
              "quarterly",
              "monthly",
              null
            ],
            "nullable": true,
            "type": "string"
          },
          "currentFiscalYear": {
            "description": "The 事業年度 containing today (YYYYMMDD), resolved like the deadline spine",
            "nullable": true,
            "properties": {
              "end": {
                "example": 20270215,
                "type": "integer"
              },
              "start": {
                "example": 20260216,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "etaxUserId": {
            "description": "利用者識別番号",
            "nullable": true,
            "type": "string"
          },
          "executiveCompensation": {
            "description": "役員報酬 月額（定期同額給与）",
            "nullable": true,
            "type": "integer"
          },
          "firstFiscalYear": {
            "description": "第1期 — the earliest ANNUAL fiscal period on file",
            "nullable": true,
            "properties": {
              "end": {
                "example": 20260215,
                "type": "integer"
              },
              "start": {
                "example": 20250606,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "fiscalYearEnd": {
            "example": 20260215,
            "nullable": true,
            "type": "integer"
          },
          "fiscalYearStart": {
            "example": 20250216,
            "nullable": true,
            "type": "integer"
          },
          "invoiceRegistrationNumber": {
            "description": "自社の適格請求書発行事業者登録番号",
            "example": "T5011003021894",
            "nullable": true,
            "type": "string"
          },
          "invoiceRegistrationVerified": {
            "type": "boolean"
          },
          "invoiceRegistrationVerifiedAt": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "isMultipleWorkplaceEmployee": {
            "description": "二以上事業所勤務（乙欄適用）",
            "nullable": true,
            "type": "boolean"
          },
          "isQualifiedInvoiceIssuer": {
            "type": "boolean"
          },
          "taxAccountantName": {
            "nullable": true,
            "type": "string"
          },
          "taxAccountantOfficeName": {
            "nullable": true,
            "type": "string"
          },
          "taxOfficeCode": {
            "nullable": true,
            "type": "string"
          },
          "taxOfficeName": {
            "nullable": true,
            "type": "string"
          }
        },
        "type": "object"
      },
      "CompanyDataSuccessResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/CompanyScrapeResponse"
          },
          "message": {
            "example": "Company data scraped successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "CompanyEvent": {
        "properties": {
          "createdAt": {
            "format": "date-time",
            "type": "string"
          },
          "deadlines": {
            "items": {
              "$ref": "#/components/schemas/CompanyEventDeadline"
            },
            "type": "array"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "kind": {
            "enum": [
              "head_office_move",
              "representative_change",
              "representative_address_change",
              "capital_change",
              "fiscal_year_change",
              "vehicle_base_change"
            ],
            "example": "representative_address_change",
            "type": "string"
          },
          "label": {
            "example": "代表者の住所が変わった",
            "type": "string"
          },
          "note": {
            "maxLength": 500,
            "nullable": true,
            "type": "string"
          },
          "occurredOn": {
            "example": "2026-06-27",
            "format": "date",
            "type": "string"
          }
        },
        "required": [
          "id",
          "kind",
          "label",
          "occurredOn",
          "note",
          "createdAt",
          "deadlines"
        ],
        "type": "object"
      },
      "CompanyEventDeadline": {
        "properties": {
          "dueDate": {
            "example": "2026-07-11",
            "format": "date",
            "type": "string"
          },
          "form": {
            "example": "代表者の住所の変更登記",
            "nullable": true,
            "type": "string"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "periodLabel": {
            "example": "ev-rec-0b8f…-touki",
            "type": "string"
          },
          "ruleKey": {
            "example": "company_event_registration",
            "type": "string"
          },
          "status": {
            "enum": [
              "upcoming",
              "due_soon",
              "overdue",
              "completed",
              "not_applicable",
              "dismissed",
              "closed"
            ],
            "type": "string"
          }
        },
        "required": [
          "id",
          "ruleKey",
          "periodLabel",
          "dueDate",
          "status",
          "form"
        ],
        "type": "object"
      },
      "CompanyEventKind": {
        "properties": {
          "hint": {
            "example": "代表者が引っ越したとき（登記事項です）",
            "type": "string"
          },
          "kind": {
            "enum": [
              "head_office_move",
              "representative_change",
              "representative_address_change",
              "capital_change",
              "fiscal_year_change",
              "vehicle_base_change"
            ],
            "example": "representative_address_change",
            "type": "string"
          },
          "label": {
            "example": "代表者の住所が変わった",
            "type": "string"
          }
        },
        "required": [
          "kind",
          "label",
          "hint"
        ],
        "type": "object"
      },
      "CompanyInfoCheckResponse": {
        "properties": {
          "data": {
            "description": "Whether user has a company info document",
            "example": true,
            "type": "boolean"
          },
          "message": {
            "example": "Company info document retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "CompanyListResponse": {
        "properties": {
          "data": {
            "items": {
              "$ref": "#/components/schemas/Company"
            },
            "type": "array"
          },
          "message": {
            "example": "Companies retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "CompanyProgress": {
        "properties": {
          "companyId": {
            "description": "Company identifier",
            "example": "comp_123456",
            "type": "string"
          },
          "companyName": {
            "description": "Company name",
            "example": "テクノロジー株式会社",
            "type": "string"
          },
          "progress": {
            "$ref": "#/components/schemas/EstablishmentProgress"
          }
        },
        "required": [
          "companyId",
          "progress"
        ],
        "type": "object"
      },
      "CompanyResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/Company"
          },
          "message": {
            "example": "Company retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "CompanyScrapeResponse": {
        "properties": {
          "address": {
            "description": "Registered business address",
            "example": "東京都渋谷区サンプル１丁目２番３号",
            "type": "string"
          },
          "companyName": {
            "description": "Official company name in Japanese",
            "example": "サンプル株式会社",
            "type": "string"
          },
          "companyNameFurigana": {
            "description": "Company name in katakana (furigana)",
            "example": "サンプルカブシキガイシャ",
            "nullable": true,
            "type": "string"
          },
          "corporateNumber": {
            "description": "Corporate number (13 digits without T prefix)",
            "example": "1234567890123",
            "type": "string"
          },
          "lastUpdated": {
            "description": "Last update date from government records",
            "example": "令和6年1月31日",
            "type": "string"
          },
          "registrationDate": {
            "description": "Invoice registration date (if available)",
            "example": "令和5年10月1日",
            "nullable": true,
            "type": "string"
          },
          "registrationNumber": {
            "description": "Invoice registration number with T prefix (if available)",
            "example": "T1234567890123",
            "nullable": true,
            "type": "string"
          }
        },
        "required": [
          "companyName",
          "companyNameFurigana",
          "corporateNumber",
          "address",
          "lastUpdated"
        ],
        "type": "object"
      },
      "CompanySetupResponse": {
        "properties": {
          "data": {
            "properties": {
              "company": {
                "$ref": "#/components/schemas/Company"
              },
              "completedAt": {
                "example": "2024-01-15T10:30:00.000Z",
                "format": "date-time",
                "type": "string"
              },
              "setupCompleted": {
                "example": true,
                "type": "boolean"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Company setup completed successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "CompanyType": {
        "description": "Company type (kk: 株式会社, llc: 合同会社)",
        "enum": [
          "kk",
          "llc"
        ],
        "example": "kk",
        "type": "string"
      },
      "CompanyTypeOption": {
        "properties": {
          "bestFor": {
            "description": "Best suited for these scenarios",
            "example": [
              "大規模事業",
              "投資家からの資金調達",
              "上場を目指す企業"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "cons": {
            "description": "Disadvantages of this company type",
            "example": [
              "設立費用が高い",
              "手続きが複雑",
              "役員任期がある"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "cost": {
            "description": "Estimated setup cost",
            "example": "約25万円",
            "type": "string"
          },
          "name": {
            "description": "Company type name",
            "example": "株式会社",
            "type": "string"
          },
          "pros": {
            "description": "Advantages of this company type",
            "example": [
              "信用度が高い",
              "資金調達しやすい",
              "上場可能"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "time": {
            "description": "Estimated setup time",
            "example": "約2-3週間",
            "type": "string"
          }
        },
        "required": [
          "name",
          "pros",
          "cons",
          "bestFor",
          "cost",
          "time"
        ],
        "type": "object"
      },
      "CompanyTypeRecommendationAPIResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/CompanyTypeRecommendationResponse"
          },
          "message": {
            "example": "会社形態の推奨を生成しました",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "CompanyTypeRecommendationRequest": {
        "$ref": "#/components/schemas/CompanyTypeRecommendationRequestBody"
      },
      "CompanyTypeRecommendationRequestBody": {
        "properties": {
          "business_type": {
            "$ref": "#/components/schemas/BusinessType"
          },
          "employee_count": {
            "$ref": "#/components/schemas/EmployeeCount"
          },
          "existing_business": {
            "description": "Whether converting from existing business",
            "example": false,
            "type": "boolean"
          },
          "expected_revenue": {
            "$ref": "#/components/schemas/ExpectedRevenue"
          },
          "funding_needs": {
            "$ref": "#/components/schemas/FundingNeeds"
          },
          "industry_license": {
            "description": "Required industry license (if any)",
            "example": "古物商許可",
            "nullable": true,
            "type": "string"
          },
          "international_business": {
            "description": "Whether planning international business",
            "example": true,
            "type": "boolean"
          },
          "solo_founder": {
            "description": "Whether the founder is working alone",
            "example": false,
            "type": "boolean"
          }
        },
        "required": [
          "business_type",
          "expected_revenue",
          "funding_needs",
          "solo_founder",
          "international_business"
        ],
        "type": "object"
      },
      "CompanyTypeRecommendationResponse": {
        "properties": {
          "kk": {
            "$ref": "#/components/schemas/CompanyTypeOption"
          },
          "llc": {
            "$ref": "#/components/schemas/CompanyTypeOption"
          },
          "reasoning": {
            "description": "Detailed reasoning for the recommendation",
            "example": "IT事業で将来的な資金調達を考慮すると、株式会社が適しています。信用度が高く、投資家からの資金調達も容易です。",
            "type": "string"
          },
          "recommendation": {
            "description": "AI recommendation",
            "enum": [
              "kk",
              "llc",
              "undecided"
            ],
            "example": "kk",
            "type": "string"
          }
        },
        "required": [
          "kk",
          "llc",
          "recommendation",
          "reasoning"
        ],
        "type": "object"
      },
      "ComplianceCheckResult": {
        "description": "Compliance check result (コンプライアンスチェック結果)",
        "properties": {
          "checks": {
            "items": {
              "properties": {
                "message": {
                  "example": "令和7年分の税額表を使用中",
                  "type": "string"
                },
                "name": {
                  "example": "tax_table_current",
                  "type": "string"
                },
                "passed": {
                  "example": true,
                  "type": "boolean"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "companyStatus": {
            "properties": {
              "isMultipleWorkplaceEmployee": {
                "example": false,
                "type": "boolean"
              },
              "kakuteishinkokuRequired": {
                "description": "確定申告必要",
                "example": false,
                "type": "boolean"
              },
              "taxColumn": {
                "enum": [
                  "kou",
                  "otsu"
                ],
                "example": "kou",
                "type": "string"
              },
              "yearEndAdjustmentEligible": {
                "description": "年末調整対象",
                "example": true,
                "type": "boolean"
              }
            },
            "type": "object"
          },
          "reminders": {
            "items": {
              "properties": {
                "deadline": {
                  "example": "2026-03-15",
                  "type": "string"
                },
                "message": {
                  "example": "乙欄のため確定申告が必要です（2月16日〜3月15日）",
                  "type": "string"
                },
                "type": {
                  "example": "kakuteishinkoku",
                  "type": "string"
                }
              },
              "type": "object"
            },
            "type": "array"
          }
        },
        "type": "object"
      },
      "ComplianceDashboard": {
        "properties": {
          "alerts": {
            "description": "Compliance alerts",
            "items": {
              "properties": {
                "message": {
                  "example": "15件の経費に適格請求書のマークがありません",
                  "type": "string"
                },
                "type": {
                  "enum": [
                    "warning",
                    "critical"
                  ],
                  "example": "warning",
                  "type": "string"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "byDocumentType": {
            "description": "Breakdown by document type",
            "items": {
              "properties": {
                "count": {
                  "description": "Total count for this type",
                  "example": 45,
                  "type": "integer"
                },
                "integrityHashedCount": {
                  "description": "Integrity-hashed count for this type",
                  "example": 38,
                  "type": "integer"
                },
                "timestampedCount": {
                  "deprecated": true,
                  "description": "Deprecated alias of integrityHashedCount — integrity-hashed, NOT 認定タイムスタンプ",
                  "example": 38,
                  "type": "integer"
                },
                "type": {
                  "description": "Document type",
                  "example": "receipt",
                  "type": "string"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "recentAuditLogs": {
            "description": "Recent audit log entries",
            "items": {
              "properties": {
                "actionType": {
                  "example": "timestamp",
                  "type": "string"
                },
                "documentId": {
                  "format": "uuid",
                  "type": "string"
                },
                "timestamp": {
                  "format": "date-time",
                  "type": "string"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "summary": {
            "properties": {
              "certifiedTsaIntegrated": {
                "description": "Always false: no accredited timestamp authority (認定TSA) is integrated",
                "enum": [
                  false
                ],
                "example": false,
                "type": "boolean"
              },
              "complianceRate": {
                "description": "Compliance rate percentage",
                "example": 76.67,
                "format": "decimal",
                "type": "number"
              },
              "compliantDocuments": {
                "description": "Number of fully compliant documents",
                "example": 115,
                "type": "integer"
              },
              "integrityHashedDocuments": {
                "description": "Number of documents with a server-side integrity hash",
                "example": 120,
                "type": "integer"
              },
              "timestampedDocuments": {
                "deprecated": true,
                "description": "Deprecated alias of integrityHashedDocuments — counts integrity-hashed documents, NOT 認定タイムスタンプ",
                "example": 120,
                "type": "integer"
              },
              "totalDocuments": {
                "description": "Total number of documents",
                "example": 150,
                "type": "integer"
              }
            },
            "type": "object"
          }
        },
        "required": [
          "summary",
          "byDocumentType",
          "recentAuditLogs",
          "alerts"
        ],
        "type": "object"
      },
      "ComplianceIssue": {
        "properties": {
          "code": {
            "description": "Issue code for programmatic handling",
            "example": "LOW_TIMESTAMP_RATE",
            "type": "string"
          },
          "message": {
            "description": "Human-readable issue description",
            "example": "タイムスタンプ付与率が50%未満です",
            "type": "string"
          },
          "recommendation": {
            "description": "Recommended action to resolve the issue",
            "example": "電子取引データにタイムスタンプを付与してください",
            "type": "string"
          },
          "severity": {
            "$ref": "#/components/schemas/ComplianceIssueSeverity"
          }
        },
        "required": [
          "severity",
          "code",
          "message",
          "recommendation"
        ],
        "type": "object"
      },
      "ComplianceIssueSeverity": {
        "description": "Compliance issue severity level",
        "enum": [
          "critical",
          "warning",
          "info"
        ],
        "example": "warning",
        "type": "string"
      },
      "ComplianceResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/ComplianceCheckResult"
          },
          "message": {
            "example": "電子帳簿保存法に準拠しています",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ComplianceRule": {
        "properties": {
          "description_ja": {
            "nullable": true,
            "type": "string"
          },
          "effective_from": {
            "format": "date",
            "type": "string"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "legal_basis": {
            "nullable": true,
            "type": "string"
          },
          "rule_key": {
            "example": "corporate_tax_filing",
            "type": "string"
          },
          "source_url": {
            "format": "uri",
            "nullable": true,
            "type": "string"
          },
          "verified_at": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "version": {
            "type": "integer"
          }
        },
        "type": "object"
      },
      "ComponentHealth": {
        "properties": {
          "lastCheck": {
            "format": "date-time",
            "type": "string"
          },
          "latencyMs": {
            "description": "Response time in milliseconds",
            "example": 5,
            "type": "number"
          },
          "message": {
            "example": "Connected",
            "type": "string"
          },
          "status": {
            "enum": [
              "healthy",
              "degraded",
              "unhealthy"
            ],
            "example": "healthy",
            "type": "string"
          }
        },
        "type": "object"
      },
      "CompressionInfo": {
        "properties": {
          "headers": {
            "properties": {
              "request": {
                "example": "Accept-Encoding: gzip, br",
                "type": "string"
              },
              "response": {
                "example": "Content-Encoding: gzip",
                "type": "string"
              }
            },
            "type": "object"
          },
          "recommendations": {
            "properties": {
              "clustering": {
                "properties": {
                  "description": {
                    "example": "Point clustering reduces feature count",
                    "type": "string"
                  },
                  "recommendation": {
                    "example": "Use cluster=true for transaction point data",
                    "type": "string"
                  }
                },
                "type": "object"
              },
              "geoJSON": {
                "properties": {
                  "description": {
                    "example": "GeoJSON compresses very well (60-80% reduction)",
                    "type": "string"
                  },
                  "recommendation": {
                    "example": "Always enable Accept-Encoding: gzip",
                    "type": "string"
                  }
                },
                "type": "object"
              },
              "simplification": {
                "properties": {
                  "description": {
                    "example": "Geometry simplification at lower zooms",
                    "type": "string"
                  },
                  "recommendation": {
                    "example": "Use simplify=true for zoom < 14",
                    "type": "string"
                  }
                },
                "type": "object"
              },
              "vectorTiles": {
                "properties": {
                  "description": {
                    "example": "MVT (Mapbox Vector Tiles) are pre-compressed",
                    "type": "string"
                  },
                  "recommendation": {
                    "example": "Use responseFormat=pbf for best performance",
                    "type": "string"
                  }
                },
                "type": "object"
              }
            },
            "type": "object"
          },
          "supported": {
            "description": "Supported compression formats",
            "example": [
              "gzip",
              "br"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          }
        },
        "required": [
          "supported",
          "recommendations",
          "headers"
        ],
        "type": "object"
      },
      "CompressionInfoResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/CompressionInfo"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "ConfidenceLevel": {
        "description": "AI confidence level for recommendations",
        "enum": [
          "high",
          "medium",
          "low"
        ],
        "example": "high",
        "type": "string"
      },
      "ConfirmFileGroupRequest": {
        "properties": {
          "document_id": {
            "description": "Optional: override or set the target document. Falls back to group.document_id if omitted.",
            "format": "uuid",
            "type": "string"
          },
          "link_type": {
            "default": "source",
            "description": "Link type for file_document_links. Defaults to \"source\".",
            "enum": [
              "attachment",
              "source",
              "source_receipt",
              "evidence",
              "supporting"
            ],
            "type": "string"
          },
          "target_document_type": {
            "description": "Optional: store this target document type on the group when confirming.",
            "example": "claims",
            "maxLength": 100,
            "type": "string"
          }
        },
        "type": "object"
      },
      "ConfirmGroupResponse": {
        "properties": {
          "data": {
            "properties": {
              "document_id": {
                "description": "ID of the linked document",
                "format": "uuid",
                "type": "string"
              },
              "files_linked": {
                "example": 3,
                "type": "integer"
              },
              "group_id": {
                "format": "uuid",
                "type": "string"
              }
            },
            "type": "object"
          },
          "message": {
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "type": "object"
      },
      "ConnectRequest": {
        "properties": {
          "provider": {
            "description": "Bank provider identifier",
            "enum": [
              "gmo_aozora"
            ],
            "example": "gmo_aozora",
            "type": "string"
          }
        },
        "required": [
          "provider"
        ],
        "type": "object"
      },
      "ConnectResponse": {
        "properties": {
          "authorizationUrl": {
            "format": "uri",
            "type": "string"
          },
          "connectionId": {
            "format": "uuid",
            "type": "string"
          }
        },
        "type": "object"
      },
      "ConsumptionTaxCalculationResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/ConsumptionTaxReturn"
          },
          "message": {
            "example": "消費税申告額を計算しました",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ConsumptionTaxHealthResponse": {
        "properties": {
          "features": {
            "example": [
              "General taxation calculation (一般課税)",
              "Simplified taxation calculation (簡易課税)",
              "2割特例 calculation (Special 20% rule)",
              "Method comparison and recommendation",
              "Quarterly summary"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "message": {
            "example": "消費税申告サポート API is running",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "features"
        ],
        "type": "object"
      },
      "ConsumptionTaxReturn": {
        "properties": {
          "businessType": {
            "$ref": "#/components/schemas/BusinessType"
          },
          "calculatedAt": {
            "description": "Calculation timestamp",
            "example": "2024-03-31T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "calculationMethod": {
            "$ref": "#/components/schemas/TaxCalculationMethod"
          },
          "finalTaxDue": {
            "description": "Final tax due amount (最終納付税額)",
            "example": 110000,
            "format": "decimal",
            "type": "number"
          },
          "fiscalYear": {
            "description": "Fiscal year",
            "example": 2024,
            "type": "integer"
          },
          "generalTaxation": {
            "$ref": "#/components/schemas/GeneralTaxationCalculation"
          },
          "isEstimate": {
            "description": "Whether this is an estimate or final calculation",
            "example": true,
            "type": "boolean"
          },
          "periodEnd": {
            "description": "Period end date",
            "example": "2024-12-31",
            "format": "date",
            "type": "string"
          },
          "periodStart": {
            "description": "Period start date",
            "example": "2024-01-01",
            "format": "date",
            "type": "string"
          },
          "recommendation": {
            "$ref": "#/components/schemas/TaxRecommendation"
          },
          "simplifiedTaxation": {
            "$ref": "#/components/schemas/SimplifiedTaxationCalculation"
          },
          "specialRule20": {
            "$ref": "#/components/schemas/SpecialRule20Calculation"
          },
          "taxSummary": {
            "description": "Tax summary by rate (税率別集計)",
            "properties": {
              "reduced8": {
                "$ref": "#/components/schemas/TaxRateSummary"
              },
              "standard10": {
                "$ref": "#/components/schemas/TaxRateSummary"
              },
              "total": {
                "$ref": "#/components/schemas/TaxRateSummary"
              }
            },
            "type": "object"
          }
        },
        "required": [
          "fiscalYear",
          "periodStart",
          "periodEnd",
          "calculationMethod",
          "taxSummary",
          "finalTaxDue",
          "calculatedAt",
          "isEstimate"
        ],
        "type": "object"
      },
      "ContextualInsightsResponse": {
        "properties": {
          "insights": {
            "items": {
              "$ref": "#/components/schemas/ProactiveInsight"
            },
            "type": "array"
          },
          "tips": {
            "items": {
              "properties": {
                "learnMoreUrl": {
                  "example": "/knowledge/document-retention",
                  "type": "string"
                },
                "message": {
                  "example": "領収書は7年間保存が必要です",
                  "type": "string"
                }
              },
              "type": "object"
            },
            "nullable": true,
            "type": "array"
          }
        },
        "type": "object"
      },
      "ConversationDetail": {
        "properties": {
          "createdAt": {
            "format": "date-time",
            "type": "string"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "messages": {
            "items": {
              "$ref": "#/components/schemas/ConversationMessage"
            },
            "type": "array"
          },
          "role": {
            "$ref": "#/components/schemas/AdvisorRole"
          },
          "title": {
            "type": "string"
          },
          "updatedAt": {
            "format": "date-time",
            "type": "string"
          }
        },
        "type": "object"
      },
      "ConversationMessage": {
        "properties": {
          "content": {
            "type": "string"
          },
          "role": {
            "enum": [
              "user",
              "assistant",
              "system"
            ],
            "type": "string"
          },
          "timestamp": {
            "format": "date-time",
            "type": "string"
          }
        },
        "type": "object"
      },
      "ConversationSummary": {
        "properties": {
          "createdAt": {
            "format": "date-time",
            "type": "string"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "messageCount": {
            "example": 4,
            "type": "integer"
          },
          "role": {
            "$ref": "#/components/schemas/AdvisorRole"
          },
          "summary": {
            "nullable": true,
            "type": "string"
          },
          "title": {
            "example": "自宅の電気代について",
            "type": "string"
          },
          "updatedAt": {
            "format": "date-time",
            "type": "string"
          }
        },
        "type": "object"
      },
      "Coordinates": {
        "properties": {
          "lat": {
            "description": "Latitude coordinate",
            "example": 35.6895,
            "format": "double",
            "maximum": 90,
            "minimum": -90,
            "type": "number"
          },
          "lng": {
            "description": "Longitude coordinate",
            "example": 139.6917,
            "format": "double",
            "maximum": 180,
            "minimum": -180,
            "type": "number"
          }
        },
        "required": [
          "lng",
          "lat"
        ],
        "type": "object"
      },
      "CoordinatesToTilesResponse": {
        "properties": {
          "data": {
            "properties": {
              "bounds": {
                "$ref": "#/components/schemas/Bounds"
              },
              "input": {
                "properties": {
                  "lat": {
                    "example": 35.6895,
                    "type": "number"
                  },
                  "lng": {
                    "example": 139.6917,
                    "type": "number"
                  },
                  "zoom": {
                    "example": 13,
                    "type": "integer"
                  }
                },
                "type": "object"
              },
              "mlitApiExample": {
                "description": "Example MLIT API URL for this tile",
                "example": "/api/compliance/real-estate/gis/XKT002?z=13&x=7274&y=3225",
                "type": "string"
              },
              "tile": {
                "$ref": "#/components/schemas/TileCoordinates"
              }
            },
            "type": "object"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "CorporateNumberBulkLookupRequest": {
        "properties": {
          "corporate_numbers": {
            "description": "Array of 13-digit corporate numbers (max 10)",
            "example": [
              "1234567890123",
              "9876543210987"
            ],
            "items": {
              "pattern": "^\\d{13}$",
              "type": "string"
            },
            "maxItems": 10,
            "type": "array"
          }
        },
        "required": [
          "corporate_numbers"
        ],
        "type": "object"
      },
      "CorporateNumberDetail": {
        "properties": {
          "address": {
            "example": "東京都渋谷区...",
            "type": "string"
          },
          "city": {
            "example": "渋谷区",
            "type": "string"
          },
          "corporate_number": {
            "example": "1234567890123",
            "type": "string"
          },
          "name": {
            "example": "株式会社サンプル",
            "type": "string"
          },
          "name_kana": {
            "example": "カブシキガイシャサンプル",
            "type": "string"
          },
          "prefecture": {
            "example": "東京都",
            "type": "string"
          },
          "registration_date": {
            "example": "2023-01-01",
            "format": "date",
            "type": "string"
          },
          "status": {
            "example": "active",
            "type": "string"
          },
          "update_date": {
            "example": "2024-01-15",
            "format": "date",
            "type": "string"
          }
        },
        "type": "object"
      },
      "CorporateNumberLookupRequest": {
        "properties": {
          "corporate_number": {
            "description": "13-digit corporate number",
            "example": "1234567890123",
            "pattern": "^\\d{13}$",
            "type": "string"
          },
          "include_history": {
            "default": false,
            "description": "Include historical corporate data",
            "example": false,
            "type": "boolean"
          }
        },
        "required": [
          "corporate_number"
        ],
        "type": "object"
      },
      "CorporateNumberResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/CorporateNumberDetail"
          },
          "message": {
            "example": "Corporate number lookup completed",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "type": "object"
      },
      "CorporateNumberSearchRequest": {
        "properties": {
          "limit": {
            "default": 10,
            "description": "Maximum number of results to return",
            "example": 10,
            "maximum": 100,
            "type": "integer"
          },
          "name": {
            "description": "Company name to search (minimum 2 characters)",
            "example": "株式会社サンプル",
            "minLength": 2,
            "type": "string"
          },
          "prefecture": {
            "description": "Prefecture to filter results",
            "example": "東京都",
            "type": "string"
          }
        },
        "required": [
          "name"
        ],
        "type": "object"
      },
      "CorporateNumberUpdatesRequest": {
        "properties": {
          "from": {
            "description": "Start date for updates (YYYY-MM-DD)",
            "example": "2024-01-01",
            "format": "date",
            "type": "string"
          },
          "prefecture": {
            "description": "Prefecture to filter updates",
            "example": "東京都",
            "type": "string"
          },
          "to": {
            "description": "End date for updates (YYYY-MM-DD)",
            "example": "2024-01-31",
            "format": "date",
            "type": "string"
          }
        },
        "required": [
          "from",
          "to"
        ],
        "type": "object"
      },
      "CorporateRegistryProfile": {
        "properties": {
          "created_at": {
            "format": "date-time",
            "type": "string"
          },
          "director_term_years": {
            "example": 2,
            "nullable": true,
            "type": "integer"
          },
          "entity_type": {
            "enum": [
              "KK",
              "GK",
              "other"
            ],
            "example": "KK",
            "type": "string"
          },
          "gk_mokuteki_josho_clause": {
            "type": "boolean"
          },
          "health_score": {
            "maximum": 100,
            "minimum": 0,
            "type": "integer"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "kessankoukoku_method": {
            "description": "決算公告方法",
            "nullable": true,
            "type": "string"
          },
          "kessankoukoku_status": {
            "nullable": true,
            "type": "string"
          },
          "last_any_registration_date": {
            "format": "date",
            "nullable": true,
            "type": "string"
          },
          "last_director_registration_date": {
            "format": "date",
            "nullable": true,
            "type": "string"
          },
          "registered_address": {
            "nullable": true,
            "type": "string"
          },
          "updated_at": {
            "format": "date-time",
            "type": "string"
          }
        },
        "type": "object"
      },
      "CorrectionRecordedResponse": {
        "properties": {
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "message": {
            "type": "string"
          },
          "newRuleCreated": {
            "description": "Whether a new user rule was auto-created",
            "type": "boolean"
          },
          "ruleUpdated": {
            "description": "Whether an existing rule confidence was adjusted",
            "type": "boolean"
          }
        },
        "type": "object"
      },
      "CounterpartyAdvice": {
        "properties": {
          "advisories": {
            "items": {
              "$ref": "#/components/schemas/Advisory"
            },
            "type": "array"
          },
          "clientId": {
            "format": "uuid",
            "type": "string"
          },
          "facts": {
            "$ref": "#/components/schemas/CounterpartyAdvisorFacts"
          },
          "profile": {
            "allOf": [
              {
                "$ref": "#/components/schemas/CounterpartyTaxProfile"
              }
            ],
            "nullable": true
          }
        },
        "required": [
          "clientId",
          "profile",
          "facts",
          "advisories"
        ],
        "type": "object"
      },
      "CounterpartyAdvisorFacts": {
        "properties": {
          "clientType": {
            "nullable": true,
            "type": "integer"
          },
          "countryCode": {
            "nullable": true,
            "type": "string"
          },
          "entityType": {
            "enum": [
              "corporation",
              "individual",
              "unknown"
            ],
            "type": "string"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "name": {
            "type": "string"
          },
          "residency": {
            "enum": [
              "domestic",
              "foreign",
              "unknown"
            ],
            "type": "string"
          },
          "residencySource": {
            "enum": [
              "profile",
              "nta_registry",
              "address"
            ],
            "nullable": true,
            "type": "string"
          },
          "treatyFormFiledOn": {
            "format": "date",
            "nullable": true,
            "type": "string"
          }
        },
        "required": [
          "id",
          "name",
          "residency",
          "residencySource",
          "countryCode",
          "entityType",
          "clientType",
          "treatyFormFiledOn"
        ],
        "type": "object"
      },
      "CounterpartyTaxProfile": {
        "properties": {
          "countryCode": {
            "example": "VN",
            "nullable": true,
            "type": "string"
          },
          "entityType": {
            "enum": [
              "corporation",
              "individual"
            ],
            "nullable": true,
            "type": "string"
          },
          "residency": {
            "enum": [
              "domestic",
              "foreign"
            ],
            "nullable": true,
            "type": "string"
          },
          "residencyDocumentNote": {
            "nullable": true,
            "type": "string"
          },
          "treatyFormFiledOn": {
            "format": "date",
            "nullable": true,
            "type": "string"
          },
          "updatedAt": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          }
        },
        "required": [
          "residency",
          "countryCode",
          "entityType",
          "treatyFormFiledOn",
          "residencyDocumentNote",
          "updatedAt"
        ],
        "type": "object"
      },
      "CreateAIPreferenceRequest": {
        "properties": {
          "account_code": {
            "example": "6290",
            "type": "string"
          },
          "account_name": {
            "example": "会議費",
            "type": "string"
          },
          "description": {
            "description": "Human-readable description",
            "example": "スターバックス・ドトール → 会議費(6290)",
            "type": "string"
          },
          "is_active": {
            "example": true,
            "type": "boolean"
          },
          "pattern": {
            "description": "Regex pattern for matching",
            "example": "(?i)(starbucks|ｽﾀｰﾊﾞｯｸｽ|ドトール)",
            "type": "string"
          },
          "preference_type": {
            "$ref": "#/components/schemas/AIPreferenceType"
          },
          "priority": {
            "example": 0,
            "type": "integer"
          },
          "scope": {
            "$ref": "#/components/schemas/AIPreferenceScope"
          },
          "tax_category": {
            "example": "課税仕入10%",
            "type": "string"
          }
        },
        "required": [
          "preference_type",
          "description"
        ],
        "type": "object"
      },
      "CreateBankAccountRequest": {
        "properties": {
          "account_holder_name": {
            "example": "ヤマダ タロウ",
            "maxLength": 100,
            "type": "string"
          },
          "account_number": {
            "example": "1234567",
            "pattern": "^\\d{7,8}$",
            "type": "string"
          },
          "account_type": {
            "enum": [
              "普通",
              "当座",
              "貯蓄"
            ],
            "example": "普通",
            "type": "string"
          },
          "bank_code": {
            "example": "0001",
            "pattern": "^\\d{4}$",
            "type": "string"
          },
          "bank_name": {
            "example": "みずほ銀行",
            "maxLength": 100,
            "type": "string"
          },
          "branch_code": {
            "example": "001",
            "pattern": "^\\d{3}$",
            "type": "string"
          },
          "branch_name": {
            "example": "東京営業部",
            "maxLength": 50,
            "type": "string"
          },
          "company_id": {
            "format": "uuid",
            "type": "string"
          },
          "display_name": {
            "example": "事業用メイン口座",
            "maxLength": 100,
            "type": "string"
          },
          "is_primary": {
            "type": "boolean"
          },
          "loan_end_date": {
            "format": "date",
            "type": "string"
          },
          "loan_interest_rate": {
            "type": "number"
          },
          "loan_lender_name": {
            "maxLength": 100,
            "type": "string"
          },
          "loan_original_amount": {
            "description": "IntJPY — no decimals",
            "minimum": 0,
            "type": "integer"
          },
          "loan_start_date": {
            "format": "date",
            "type": "string"
          },
          "loan_type": {
            "enum": [
              "bank",
              "director_to_company",
              "company_to_director",
              "policy",
              "other"
            ],
            "type": "string"
          },
          "purpose": {
            "default": "business",
            "enum": [
              "business",
              "personal",
              "reimbursement",
              "loan",
              "savings",
              "tax_payment",
              "payroll",
              "deposit",
              "other"
            ],
            "type": "string"
          },
          "sort_order": {
            "default": 0,
            "minimum": 0,
            "type": "integer"
          }
        },
        "required": [
          "bank_name",
          "account_holder_name"
        ],
        "type": "object"
      },
      "CreateBankStatementRequest": {
        "properties": {
          "balance": {
            "description": "Account balance after transaction in JPY cents",
            "example": 125000000,
            "type": "integer"
          },
          "category": {
            "$ref": "#/components/schemas/TransactionCategory"
          },
          "deposit_amount": {
            "description": "Deposit amount in JPY cents (optional)",
            "example": 30000000,
            "minimum": 0,
            "type": "integer"
          },
          "description": {
            "description": "Transaction description or memo",
            "example": "振込 タナカ タロウ",
            "maxLength": 255,
            "type": "string"
          },
          "memo": {
            "description": "User note (手動追加 「メモ」). Whitespace-sanitized like PATCH /memo; omitted = no note.",
            "example": "中間納付 法人税",
            "maxLength": 500,
            "nullable": true,
            "type": "string"
          },
          "transaction_date": {
            "description": "Transaction date in YYYYMMDD format",
            "example": 20240115,
            "maximum": 99991231,
            "minimum": 19700101,
            "type": "integer"
          },
          "withdrawal_amount": {
            "description": "Withdrawal amount in JPY cents (optional)",
            "example": 0,
            "minimum": 0,
            "type": "integer"
          }
        },
        "required": [
          "transaction_date",
          "description",
          "balance",
          "category"
        ],
        "type": "object"
      },
      "CreateBooksShareRequest": {
        "properties": {
          "allow_audit_pack": {
            "type": "boolean"
          },
          "expires_at": {
            "format": "date-time",
            "type": "string"
          },
          "expires_in_days": {
            "maximum": 365,
            "minimum": 1,
            "type": "integer"
          },
          "fiscal_year": {
            "maximum": 2100,
            "minimum": 2000,
            "type": "integer"
          },
          "label": {
            "maxLength": 100,
            "type": "string"
          },
          "password": {
            "maxLength": 72,
            "minLength": 8,
            "type": "string"
          }
        },
        "required": [
          "password"
        ],
        "type": "object"
      },
      "CreateCategoryRuleRequest": {
        "example": {
          "base_confidence": 0.9,
          "match_pattern": "カインズホーム草津店",
          "priority": 80,
          "rule_name": "カインズ草津店 → 消耗品費",
          "rule_type": "vendor",
          "suggested_category": 9
        },
        "properties": {
          "base_confidence": {
            "default": 0.85,
            "maximum": 0.98,
            "minimum": 0.3,
            "type": "number"
          },
          "match_pattern": {
            "maxLength": 500,
            "minLength": 1,
            "type": "string"
          },
          "priority": {
            "default": 75,
            "maximum": 100,
            "minimum": 1,
            "type": "integer"
          },
          "rule_description": {
            "maxLength": 2000,
            "type": "string"
          },
          "rule_name": {
            "maxLength": 200,
            "type": "string"
          },
          "rule_type": {
            "$ref": "#/components/schemas/CategoryRuleType"
          },
          "secondary_pattern": {
            "description": "For combined rules only",
            "maxLength": 500,
            "type": "string"
          },
          "suggested_category": {
            "maximum": 26,
            "minimum": 0,
            "type": "integer"
          }
        },
        "required": [
          "rule_type",
          "match_pattern",
          "suggested_category"
        ],
        "type": "object"
      },
      "CreateClientRequest": {
        "properties": {
          "address": {
            "description": "Company address",
            "example": "東京都渋谷区サンプル１丁目２番３号",
            "maxLength": 255,
            "nullable": true,
            "type": "string"
          },
          "client_type": {
            "description": "Client type",
            "enum": [
              0,
              1,
              2
            ],
            "example": 0,
            "nullable": true,
            "type": "number"
          },
          "contact_person": {
            "description": "Primary contact person name",
            "example": "山田太郎",
            "maxLength": 255,
            "type": "string"
          },
          "corporate_number": {
            "description": "Japanese corporate number (13 digits, with or without T prefix)",
            "example": "1234567890123",
            "maxLength": 255,
            "type": "string"
          },
          "email": {
            "description": "Contact email address",
            "example": "contact@example.co.jp",
            "format": "email",
            "maxLength": 255,
            "nullable": true,
            "type": "string"
          },
          "furigana": {
            "description": "Company name in katakana (furigana)",
            "example": "サンプルカブシキガイシャ",
            "maxLength": 255,
            "nullable": true,
            "type": "string"
          },
          "name": {
            "description": "Official client company name",
            "example": "サンプル株式会社",
            "maxLength": 255,
            "type": "string"
          },
          "phone": {
            "description": "Contact phone number",
            "example": "03-0000-0000",
            "maxLength": 255,
            "nullable": true,
            "type": "string"
          },
          "registration_number": {
            "description": "Invoice registration number with T prefix",
            "example": "T1234567890123",
            "maxLength": 255,
            "nullable": true,
            "type": "string"
          }
        },
        "required": [
          "name",
          "corporate_number",
          "contact_person"
        ],
        "type": "object"
      },
      "CreateClientSuccessResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/ClientResponse"
          },
          "message": {
            "example": "Client created successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 201,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "CreateCompanyEventRequest": {
        "properties": {
          "kind": {
            "enum": [
              "head_office_move",
              "representative_change",
              "representative_address_change",
              "capital_change",
              "fiscal_year_change",
              "vehicle_base_change"
            ],
            "example": "representative_address_change",
            "type": "string"
          },
          "note": {
            "maxLength": 500,
            "nullable": true,
            "type": "string"
          },
          "occurredOn": {
            "description": "The day it happened; every window counts from it.",
            "format": "date",
            "type": "string"
          }
        },
        "required": [
          "kind",
          "occurredOn"
        ],
        "type": "object"
      },
      "CreateCreditCardRequest": {
        "properties": {
          "brand": {
            "description": "Card brand",
            "enum": [
              "VISA",
              "Mastercard",
              "JCB",
              "AMEX",
              "Diners"
            ],
            "type": "string"
          },
          "card_name": {
            "description": "Display name for the card",
            "example": "楽天カード（メイン）",
            "maxLength": 100,
            "type": "string"
          },
          "closing_day": {
            "description": "Statement closing day (締め日)",
            "example": 15,
            "maximum": 31,
            "minimum": 1,
            "type": "integer"
          },
          "color": {
            "description": "Hex color for UI display",
            "example": "#6366f1",
            "pattern": "^#[0-9A-Fa-f]{6}$",
            "type": "string"
          },
          "company_id": {
            "description": "Associate with company",
            "format": "uuid",
            "type": "string"
          },
          "icon": {
            "description": "Icon identifier",
            "maxLength": 50,
            "type": "string"
          },
          "issuer": {
            "description": "Card issuer name",
            "example": "楽天カード株式会社",
            "maxLength": 50,
            "type": "string"
          },
          "last_four_digits": {
            "description": "Last 4 digits of card number",
            "example": "1234",
            "pattern": "^\\d{4}$",
            "type": "string"
          },
          "linked_bank_account_id": {
            "description": "Bank account ID for automatic payment (引落口座)",
            "format": "uuid",
            "type": "string"
          },
          "notes": {
            "description": "User notes",
            "maxLength": 500,
            "type": "string"
          },
          "payment_day": {
            "description": "Payment due day (引落日)",
            "example": 10,
            "maximum": 31,
            "minimum": 1,
            "type": "integer"
          }
        },
        "required": [
          "card_name",
          "last_four_digits"
        ],
        "type": "object"
      },
      "CreateDependentInput": {
        "properties": {
          "birth_date": {
            "description": "YYYYMMDD",
            "type": "integer"
          },
          "estimated_income": {
            "default": 0,
            "minimum": 0,
            "type": "integer"
          },
          "is_disabled": {
            "default": false,
            "type": "boolean"
          },
          "is_elderly": {
            "default": false,
            "type": "boolean"
          },
          "is_specific": {
            "default": false,
            "type": "boolean"
          },
          "is_spouse": {
            "default": false,
            "type": "boolean"
          },
          "lives_together": {
            "default": true,
            "type": "boolean"
          },
          "name": {
            "maxLength": 255,
            "type": "string"
          },
          "name_kana": {
            "maxLength": 255,
            "type": "string"
          },
          "overseas": {
            "default": false,
            "type": "boolean"
          },
          "relationship": {
            "description": "続柄",
            "maxLength": 50,
            "type": "string"
          }
        },
        "required": [
          "name",
          "relationship"
        ],
        "type": "object"
      },
      "CreateDocumentRelationshipRequest": {
        "description": "Request body for creating a document relationship",
        "properties": {
          "childDocumentId": {
            "description": "ID of the child document to link",
            "example": "789e0123-e89b-12d3-a456-426614174002",
            "format": "uuid",
            "type": "string"
          },
          "relationshipMetadata": {
            "additionalProperties": true,
            "description": "Optional metadata about the relationship",
            "type": "object"
          },
          "relationshipType": {
            "description": "Type of relationship",
            "enum": [
              "quotation_to_order",
              "order_to_delivery",
              "delivery_to_invoice",
              "quotation_to_invoice",
              "buyer_attachment",
              "supporting_document",
              "revision_of",
              "supersedes",
              "references",
              "related_to"
            ],
            "example": "quotation_to_invoice",
            "type": "string"
          }
        },
        "required": [
          "childDocumentId",
          "relationshipType"
        ],
        "type": "object"
      },
      "CreateDocumentRelationshipResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/DocumentRelationship"
          },
          "message": {
            "example": "Document relationship created successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 201,
            "type": "number"
          }
        },
        "type": "object"
      },
      "CreateDocumentRequest": {
        "properties": {
          "clientId": {
            "description": "Optional: Link document to a client (trading partner) on creation",
            "example": "550e8400-e29b-41d4-a716-446655440000",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "document_name": {
            "description": "Document name (required)",
            "example": "New Sales Invoice",
            "minLength": 1,
            "type": "string"
          },
          "type": {
            "description": "Document type (required)",
            "enum": [
              "sales_quotation",
              "purchase_order",
              "delivery_note",
              "sales_invoice",
              "service_agreement",
              "travel",
              "claims",
              "fixed_asset",
              "payment",
              "salary_slip",
              "tax_journal",
              "tax_general_ledger",
              "tax_trial_balance",
              "tax_financial_statements",
              "tax_balance_sheet",
              "tax_profit_loss_statement",
              "tax_cash_flow_statement",
              "tax_shareholders_equity",
              "tax_notes_financial_statements",
              "tax_corporate",
              "tax_local",
              "tax_account_breakdown",
              "tax_application_details",
              "tax_business_overview",
              "company_info",
              "company_decision",
              "company_representative",
              "company_capital",
              "company_office_location",
              "rules_claims"
            ],
            "example": "sales_invoice",
            "type": "string"
          }
        },
        "required": [
          "document_name",
          "type"
        ],
        "type": "object"
      },
      "CreateDocumentTemplateBody": {
        "properties": {
          "description": {
            "type": "string"
          },
          "name": {
            "type": "string"
          },
          "template_json": {
            "description": "Field layout JSON matching src/common/templates/*.json conventions",
            "type": "object"
          }
        },
        "required": [
          "name",
          "template_json"
        ],
        "type": "object"
      },
      "CreateEmployeeInput": {
        "properties": {
          "address_city": {
            "maxLength": 100,
            "type": "string"
          },
          "address_line": {
            "maxLength": 500,
            "type": "string"
          },
          "address_prefecture": {
            "maxLength": 50,
            "type": "string"
          },
          "allowances": {
            "description": "各種手当",
            "type": "object"
          },
          "base_salary": {
            "description": "基本給 (monthly yen)",
            "minimum": 0,
            "type": "integer"
          },
          "birth_date": {
            "description": "生年月日 YYYYMMDD — 介護保険40歳/65歳・厚年70歳・健保75歳の資格判定（前日主義）",
            "type": "integer"
          },
          "company_id": {
            "format": "uuid",
            "type": "string"
          },
          "department": {
            "maxLength": 100,
            "type": "string"
          },
          "dependents_count": {
            "default": 0,
            "minimum": 0,
            "type": "integer"
          },
          "email": {
            "format": "email",
            "type": "string"
          },
          "employee_number": {
            "description": "社員番号",
            "maxLength": 50,
            "type": "string"
          },
          "employment_status": {
            "default": "active",
            "enum": [
              "active",
              "on_leave",
              "retired",
              "pending_start"
            ],
            "type": "string"
          },
          "executive_compensation": {
            "description": "役員報酬 (monthly yen)",
            "minimum": 0,
            "type": "integer"
          },
          "is_representative": {
            "default": false,
            "type": "boolean"
          },
          "is_year_end_adjustment_target": {
            "default": true,
            "type": "boolean"
          },
          "join_date": {
            "description": "YYYYMMDD format",
            "type": "integer"
          },
          "name": {
            "description": "氏名",
            "maxLength": 255,
            "type": "string"
          },
          "name_kana": {
            "description": "氏名（カナ）",
            "maxLength": 255,
            "type": "string"
          },
          "phone": {
            "maxLength": 20,
            "type": "string"
          },
          "position_title": {
            "maxLength": 100,
            "type": "string"
          },
          "position_type": {
            "default": "regular_employee",
            "enum": [
              "representative_director",
              "director",
              "auditor",
              "executive_officer",
              "representative_member",
              "managing_member",
              "employee_director",
              "regular_employee",
              "contract_employee",
              "part_time",
              "temporary",
              "sole_proprietor",
              "family_employee",
              "advisor",
              "other"
            ],
            "type": "string"
          },
          "postal_code": {
            "maxLength": 10,
            "type": "string"
          },
          "spouse_deduction": {
            "default": false,
            "type": "boolean"
          }
        },
        "required": [
          "name"
        ],
        "type": "object"
      },
      "CreateFileGroupRequest": {
        "properties": {
          "description": {
            "example": "1月分の交通費と食費の領収書",
            "maxLength": 1000,
            "type": "string"
          },
          "document_id": {
            "description": "Optional: link to an existing document",
            "format": "uuid",
            "type": "string"
          },
          "group_type": {
            "default": "manual",
            "enum": [
              "manual",
              "ai_suggested",
              "auto_session"
            ],
            "type": "string"
          },
          "label": {
            "example": "1月の領収書",
            "maxLength": 255,
            "type": "string"
          },
          "source_session_id": {
            "format": "uuid",
            "type": "string"
          },
          "target_document_type": {
            "example": "claims",
            "type": "string"
          },
          "total_amount": {
            "example": 5500,
            "minimum": 0,
            "type": "integer"
          }
        },
        "required": [
          "label"
        ],
        "type": "object"
      },
      "CreateFileUploadRequest": {
        "properties": {
          "ai_data": {
            "additionalProperties": true,
            "description": "Optional AI-extracted data",
            "type": "object"
          },
          "bucket": {
            "description": "Supabase storage bucket name (required)",
            "example": "invoices",
            "type": "string"
          },
          "confirmed_data": {
            "additionalProperties": true,
            "description": "Optional user-confirmed data",
            "type": "object"
          },
          "file_metadata": {
            "description": "Optional file metadata and storage information",
            "properties": {
              "bucketName": {
                "type": "string"
              },
              "filePath": {
                "type": "string"
              },
              "fileSize": {
                "type": "number"
              },
              "originalFileName": {
                "type": "string"
              },
              "sanitizedFileName": {
                "type": "string"
              }
            },
            "type": "object"
          },
          "file_name": {
            "description": "Original file name (required)",
            "example": "receipt_2024_01_15.jpg",
            "minLength": 1,
            "type": "string"
          },
          "file_type": {
            "description": "File type classification (required)",
            "enum": [
              "image",
              "pdf",
              "docx"
            ],
            "example": "image",
            "type": "string"
          },
          "file_url": {
            "description": "Supabase storage URL for the file (required)",
            "example": "https://supabase.co/storage/v1/object/public/invoices/user123/receipt.jpg",
            "format": "uri",
            "type": "string"
          },
          "folder_id": {
            "description": "Optional folder ID for organization",
            "example": "456e7890-f12a-34b5-c678-901234567890",
            "format": "uuid",
            "type": "string"
          },
          "status": {
            "description": "Initial file status (optional, defaults to storage)",
            "enum": [
              "storage",
              "processed"
            ],
            "example": "storage",
            "type": "string"
          }
        },
        "required": [
          "file_name",
          "file_url",
          "bucket",
          "file_type"
        ],
        "type": "object"
      },
      "CreateFiscalPeriodRequest": {
        "properties": {
          "end_date": {
            "description": "Period end date in YYYYMMDD format",
            "example": 20240930,
            "type": "integer"
          },
          "fiscal_year": {
            "description": "Fiscal year",
            "example": 2024,
            "type": "integer"
          },
          "is_year_end": {
            "default": false,
            "description": "Whether this is a year-end period",
            "example": false,
            "type": "boolean"
          },
          "name": {
            "description": "Fiscal period name",
            "example": "2024年度第2四半期",
            "minLength": 1,
            "type": "string"
          },
          "notes": {
            "description": "Optional notes for the period",
            "example": "Second quarter with mid-year adjustments",
            "type": "string"
          },
          "period_number": {
            "description": "Period number within fiscal year",
            "example": 2,
            "type": "integer"
          },
          "start_date": {
            "description": "Period start date in YYYYMMDD format",
            "example": 20240701,
            "type": "integer"
          }
        },
        "required": [
          "name",
          "start_date",
          "end_date",
          "fiscal_year",
          "period_number"
        ],
        "type": "object"
      },
      "CreateFixedAssetFromTransactionRequest": {
        "properties": {
          "bank_transaction_id": {
            "description": "Bank transaction ID to link to the fixed asset",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "classification": {
            "$ref": "#/components/schemas/AssetClassification",
            "description": "Asset classification (required)"
          },
          "company_id": {
            "description": "Company ID for multi-company support",
            "format": "uuid",
            "type": "string"
          },
          "depreciation_method": {
            "$ref": "#/components/schemas/DepreciationMethod",
            "description": "Depreciation method (required)"
          },
          "document_id": {
            "description": "Associated document ID (invoice, receipt, etc.)",
            "format": "uuid",
            "type": "string"
          },
          "in_service_date": {
            "description": "事業供用日 (YYYYMMDD), optional. The bank row gives the payment date; depreciation and the 少額 / 一括 decision run from the day the asset went into use (法令59①). Must be a real date on or after the payment date. Omitted → depreciation starts at the payment date.",
            "example": 20260110,
            "type": "integer"
          },
          "location": {
            "description": "Physical location",
            "example": "本社駐車場",
            "type": "string"
          },
          "name": {
            "description": "Asset name or description",
            "example": "ジムニー中古車",
            "maxLength": 255,
            "type": "string"
          },
          "remarks": {
            "description": "Additional remarks",
            "example": "営業用車両",
            "type": "string"
          },
          "useful_life": {
            "description": "Useful life in years",
            "example": 6,
            "type": "integer"
          }
        },
        "required": [
          "bank_transaction_id",
          "name",
          "classification",
          "depreciation_method"
        ],
        "type": "object"
      },
      "CreateFixedAssetRequest": {
        "properties": {
          "acquisition_cost": {
            "description": "Original acquisition cost in Japanese Yen (required)",
            "example": 150000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "acquisition_date": {
            "description": "Asset acquisition date in YYYYMMDD format (required)",
            "example": 20240115,
            "maximum": 99991231,
            "minimum": 19000101,
            "type": "integer"
          },
          "classification": {
            "$ref": "#/components/schemas/AssetClassification",
            "description": "Asset classification according to Japanese tax law (required)"
          },
          "closing_book_value": {
            "description": "Expected closing book value (required)",
            "example": 120000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "depreciation_cost": {
            "description": "Annual depreciation amount (required)",
            "example": 30000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "depreciation_method": {
            "$ref": "#/components/schemas/DepreciationMethod",
            "description": "Depreciation calculation method (required)"
          },
          "document_id": {
            "description": "Associated document ID for purchase documentation (required)",
            "example": "456e7890-f12a-34b5-c678-901234567890",
            "format": "uuid",
            "type": "string"
          },
          "in_service_date": {
            "description": "事業供用日 (YYYYMMDD), optional. Must be a real date on or after acquisition_date. Omit when the asset went into use on the acquisition date.",
            "example": 20240201,
            "type": "integer"
          },
          "location": {
            "description": "Physical location of the asset (required)",
            "example": "本社 3階 営業部",
            "maxLength": 255,
            "type": "string"
          },
          "name": {
            "description": "Asset name or description (required)",
            "example": "デスクトップコンピュータ Dell OptiPlex 7090",
            "maxLength": 255,
            "minLength": 1,
            "type": "string"
          },
          "opening_book_value": {
            "description": "Initial book value (required)",
            "example": 150000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "quantity": {
            "description": "Number of asset units (required)",
            "example": 1,
            "minimum": 1,
            "type": "integer"
          },
          "remarks": {
            "description": "Additional notes or remarks",
            "example": "保証期間: 2027年1月まで",
            "maxLength": 255,
            "type": "string"
          },
          "unit": {
            "description": "Unit of measurement (required)",
            "example": "台",
            "type": "string"
          },
          "useful_life": {
            "description": "Useful life in years for depreciation (required)",
            "example": 4,
            "minimum": 1,
            "type": "integer"
          }
        },
        "required": [
          "name",
          "acquisition_date",
          "acquisition_cost",
          "document_id",
          "quantity",
          "unit",
          "opening_book_value",
          "closing_book_value",
          "useful_life",
          "depreciation_cost",
          "location",
          "classification",
          "depreciation_method"
        ],
        "type": "object"
      },
      "CreateFolderRequest": {
        "properties": {
          "color": {
            "description": "Folder color (hex code or color name)",
            "example": "#3B82F6",
            "type": "string"
          },
          "description": {
            "description": "Folder description",
            "example": "Contains all financial documents and receipts",
            "maxLength": 200,
            "type": "string"
          },
          "document_id": {
            "description": "Associated document identifier",
            "example": "abc12345-def6-7890-ghij-klmnopqrstuv",
            "format": "uuid",
            "type": "string"
          },
          "icon": {
            "description": "Folder icon identifier",
            "example": "folder-documents",
            "type": "string"
          },
          "name": {
            "description": "Folder name (required)",
            "example": "Financial Documents",
            "maxLength": 50,
            "minLength": 1,
            "type": "string"
          },
          "parent_id": {
            "description": "Parent folder identifier (optional, null for root folder)",
            "example": "456e7890-f12a-34b5-c678-901234567890",
            "format": "uuid",
            "type": "string"
          }
        },
        "required": [
          "name"
        ],
        "type": "object"
      },
      "CreateFromExpense": {
        "properties": {
          "autoCreateJournal": {
            "default": false,
            "type": "boolean"
          },
          "expenseId": {
            "format": "uuid",
            "type": "string"
          }
        },
        "required": [
          "expenseId"
        ],
        "type": "object"
      },
      "CreateInventoryItem": {
        "properties": {
          "category": {
            "$ref": "#/components/schemas/InventoryCategory"
          },
          "itemClass": {
            "$ref": "#/components/schemas/InventoryItemClass"
          },
          "name": {
            "type": "string"
          }
        },
        "required": [
          "name",
          "category"
        ],
        "type": "object"
      },
      "CreateJournalTemplateRequest": {
        "properties": {
          "credit_account_id": {
            "description": "Credit account ID",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "debit_account_id": {
            "description": "Debit account ID",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "default_amount": {
            "description": "Default amount (optional)",
            "example": 1000,
            "type": "number"
          },
          "default_description": {
            "description": "Default journal entry description",
            "example": "交通費",
            "type": "string"
          },
          "description": {
            "description": "Template description",
            "example": "電車・バス・タクシーなどの交通費",
            "type": "string"
          },
          "name": {
            "description": "Template name (e.g., \"交通費精算\")",
            "example": "交通費精算",
            "maxLength": 100,
            "type": "string"
          },
          "shortcut_key": {
            "description": "Shortcut key (F1-F5)",
            "example": "F1",
            "maxLength": 10,
            "type": "string"
          },
          "tax_included": {
            "default": false,
            "description": "Whether tax is included in amount",
            "example": false,
            "type": "boolean"
          },
          "tax_rate": {
            "$ref": "#/components/schemas/TaxRate"
          }
        },
        "required": [
          "name",
          "debit_account_id",
          "credit_account_id"
        ],
        "type": "object"
      },
      "CreateNotificationRequest": {
        "properties": {
          "notification": {
            "properties": {
              "actions": {
                "items": {
                  "$ref": "#/components/schemas/NotificationAction"
                },
                "type": "array"
              },
              "category": {
                "$ref": "#/components/schemas/NotificationCategory"
              },
              "data": {
                "type": "object"
              },
              "delivery": {
                "$ref": "#/components/schemas/NotificationDelivery"
              },
              "externalUrl": {
                "format": "uri",
                "type": "string"
              },
              "message": {
                "maxLength": 1000,
                "type": "string"
              },
              "priority": {
                "$ref": "#/components/schemas/NotificationPriority"
              },
              "relatedIds": {
                "$ref": "#/components/schemas/NotificationRelatedIds"
              },
              "scheduling": {
                "$ref": "#/components/schemas/NotificationScheduling"
              },
              "sender": {
                "$ref": "#/components/schemas/NotificationSender"
              },
              "title": {
                "maxLength": 255,
                "type": "string"
              },
              "type": {
                "$ref": "#/components/schemas/NotificationType"
              },
              "url": {
                "type": "string"
              }
            },
            "required": [
              "type",
              "title",
              "message",
              "category",
              "priority"
            ],
            "type": "object"
          },
          "options": {
            "properties": {
              "batchId": {
                "format": "uuid",
                "type": "string"
              },
              "sendImmediate": {
                "default": true,
                "type": "boolean"
              },
              "trackDelivery": {
                "default": true,
                "type": "boolean"
              }
            },
            "type": "object"
          },
          "recipients": {
            "description": "Array of recipient user IDs",
            "items": {
              "format": "uuid",
              "type": "string"
            },
            "maxItems": 100,
            "minItems": 1,
            "type": "array"
          }
        },
        "required": [
          "notification",
          "recipients"
        ],
        "type": "object"
      },
      "CreateOpeningBalanceRequest": {
        "properties": {
          "description": {
            "description": "Opening balance entry description",
            "example": "令和6年度 期首残高",
            "type": "string"
          },
          "entry_date": {
            "description": "Entry date in YYYYMMDD format (typically fiscal year start)",
            "example": 20240401,
            "maximum": 99991231,
            "minimum": 19000101,
            "type": "integer"
          },
          "lines": {
            "description": "Opening balance line items for each account",
            "items": {
              "$ref": "#/components/schemas/OpeningBalanceLine"
            },
            "minItems": 1,
            "type": "array"
          }
        },
        "required": [
          "entry_date",
          "lines"
        ],
        "type": "object"
      },
      "CreateOrUpdateBankAccountSettingsRequest": {
        "properties": {
          "account_holder_name": {
            "description": "Account holder name (required)",
            "example": "ヤマダ タロウ",
            "maxLength": 100,
            "type": "string"
          },
          "account_number": {
            "description": "Bank account number (7-8 digits)",
            "example": "1234567",
            "pattern": "^\\d{7,8}$",
            "type": "string"
          },
          "account_type": {
            "description": "Japanese bank account type",
            "enum": [
              "普通",
              "当座",
              "貯蓄"
            ],
            "example": "普通",
            "type": "string"
          },
          "bank_code": {
            "description": "Japanese bank code (4 digits)",
            "example": "0001",
            "pattern": "^\\d{4}$",
            "type": "string"
          },
          "bank_name": {
            "description": "Bank name (required)",
            "example": "みずほ銀行",
            "maxLength": 100,
            "type": "string"
          },
          "branch_code": {
            "description": "Bank branch code (3 digits)",
            "example": "001",
            "pattern": "^\\d{3}$",
            "type": "string"
          },
          "branch_name": {
            "description": "Bank branch name",
            "example": "東京営業部",
            "maxLength": 50,
            "type": "string"
          },
          "company_id": {
            "description": "Company identifier (optional)",
            "example": "123e4567-e89b-12d3-a456-426614174001",
            "format": "uuid",
            "type": "string"
          }
        },
        "required": [
          "bank_name",
          "account_holder_name"
        ],
        "type": "object"
      },
      "CreatePaySlipItemRequest": {
        "properties": {
          "amount": {
            "description": "Item amount in JPY",
            "example": 250000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "is_earning": {
            "description": "Whether this item is an earning (true) or deduction (false)",
            "example": true,
            "type": "boolean"
          },
          "item_name": {
            "description": "Pay slip item name",
            "example": "基本給",
            "maxLength": 255,
            "type": "string"
          },
          "notes": {
            "description": "Additional notes for the item",
            "example": "Monthly base salary",
            "maxLength": 500,
            "type": "string"
          },
          "type": {
            "$ref": "#/components/schemas/PaySlipItemType"
          }
        },
        "required": [
          "type",
          "item_name",
          "amount",
          "is_earning"
        ],
        "type": "object"
      },
      "CreatePaySlipRequest": {
        "properties": {
          "document_id": {
            "description": "Associated document ID",
            "example": "456e7890-f12a-34b5-c678-901234567890",
            "format": "uuid",
            "type": "string"
          },
          "employee_department": {
            "description": "Employee department",
            "example": "営業部",
            "maxLength": 255,
            "type": "string"
          },
          "employee_name": {
            "description": "Employee name",
            "example": "田中太郎",
            "maxLength": 255,
            "type": "string"
          },
          "gross_salary": {
            "description": "Gross salary amount in JPY",
            "example": 350000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "items": {
            "description": "Pay slip items (earnings and deductions)",
            "items": {
              "$ref": "#/components/schemas/CreatePaySlipItemRequest"
            },
            "maxItems": 50,
            "minItems": 1,
            "type": "array"
          },
          "net_pay": {
            "description": "Net pay amount in JPY",
            "example": 265000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "pay_period_end": {
            "description": "Pay period end date in YYYYMMDD format",
            "example": 20240131,
            "maximum": 99991231,
            "minimum": 19700101,
            "type": "integer"
          },
          "pay_period_start": {
            "description": "Pay period start date in YYYYMMDD format",
            "example": 20240101,
            "maximum": 99991231,
            "minimum": 19700101,
            "type": "integer"
          },
          "payment_date": {
            "description": "Payment date in YYYYMMDD format",
            "example": 20240225,
            "maximum": 99991231,
            "minimum": 19700101,
            "type": "integer"
          },
          "payment_type": {
            "$ref": "#/components/schemas/PaymentType",
            "description": "支払種別 (Payment Type) - auto-detected from item names if not provided"
          },
          "provision_note": {
            "description": "Additional provision notes",
            "example": "Overtime pay included for January",
            "maxLength": 1000,
            "type": "string"
          },
          "total_deductions": {
            "description": "Total deductions amount in JPY",
            "example": 85000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "ytd_gross": {
            "description": "Year-to-date gross amount in JPY",
            "example": 1050000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "ytd_income_tax": {
            "description": "Year-to-date income tax amount in JPY",
            "example": 85000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "ytd_social_ins": {
            "description": "Year-to-date social insurance amount in JPY",
            "example": 150000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "ytd_taxable": {
            "description": "Year-to-date taxable amount in JPY",
            "example": 1000000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          }
        },
        "required": [
          "employee_name",
          "employee_department",
          "pay_period_start",
          "pay_period_end",
          "gross_salary",
          "total_deductions",
          "net_pay",
          "items"
        ],
        "type": "object"
      },
      "CreateProfessionalEngagementRequest": {
        "properties": {
          "contact_note": {
            "maxLength": 500,
            "nullable": true,
            "type": "string"
          },
          "display_name": {
            "maxLength": 150,
            "minLength": 1,
            "type": "string"
          },
          "engagement_how": {
            "maxLength": 4000,
            "nullable": true,
            "type": "string"
          },
          "engagement_what": {
            "maxLength": 4000,
            "nullable": true,
            "type": "string"
          },
          "engagement_when": {
            "maxLength": 4000,
            "nullable": true,
            "type": "string"
          },
          "engagement_where": {
            "maxLength": 4000,
            "nullable": true,
            "type": "string"
          },
          "engagement_who": {
            "maxLength": 4000,
            "nullable": true,
            "type": "string"
          },
          "engagement_why": {
            "maxLength": 4000,
            "nullable": true,
            "type": "string"
          },
          "fiscal_year": {
            "maximum": 2100,
            "minimum": 2000,
            "nullable": true,
            "type": "integer"
          },
          "notes": {
            "maxLength": 4000,
            "nullable": true,
            "type": "string"
          },
          "office_name": {
            "maxLength": 150,
            "nullable": true,
            "type": "string"
          },
          "professional_type": {
            "enum": [
              "TAX_ACCOUNTANT",
              "AUDITOR",
              "LAWYER",
              "JUDICIAL_SCRIVENER",
              "SOCIAL_INSURANCE",
              "OTHER"
            ],
            "type": "string"
          },
          "status": {
            "enum": [
              "considering",
              "requested",
              "engaged",
              "completed",
              "declined"
            ],
            "type": "string"
          }
        },
        "required": [
          "display_name"
        ],
        "type": "object"
      },
      "CreatePropertyRequest": {
        "properties": {
          "address": {
            "type": "string"
          },
          "name": {
            "type": "string"
          },
          "occupant_type": {
            "enum": [
              "director",
              "employee"
            ],
            "type": "string"
          },
          "workplace_prefecture": {
            "description": "勤務地の都道府県 — the official name (「東京都」), never 「東京」 or the JIS code. Selects the 社会保険 現物給与 row; null clears it.",
            "enum": [
              "群馬県",
              "埼玉県",
              "千葉県",
              "東京都",
              "神奈川県",
              "新潟県",
              "富山県",
              "石川県",
              "福井県",
              "山梨県",
              "長野県",
              "岐阜県",
              "静岡県",
              "愛知県",
              "三重県",
              "滋賀県",
              "京都府",
              "大阪府",
              "兵庫県",
              "奈良県",
              "和歌山県",
              "鳥取県",
              "島根県",
              "岡山県",
              "広島県",
              "山口県",
              "徳島県",
              "香川県",
              "愛媛県",
              "高知県",
              "福岡県",
              "佐賀県",
              "長崎県",
              "熊本県",
              "大分県",
              "宮崎県",
              "鹿児島県",
              "沖縄県",
              "北海道",
              "青森県",
              "岩手県",
              "宮城県",
              "秋田県",
              "山形県",
              "福島県",
              "茨城県",
              "栃木県"
            ],
            "nullable": true,
            "type": "string"
          }
        },
        "required": [
          "name",
          "address"
        ],
        "type": "object"
      },
      "CreateRemarkRequest": {
        "properties": {
          "linked_account_id": {
            "description": "Optional linked account ID for categorization",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "linked_category": {
            "description": "Optional linked expense category",
            "example": 3,
            "type": "integer"
          },
          "reading": {
            "description": "Reading (フリガナ) for Japanese text",
            "example": "でんしゃだい",
            "type": "string"
          },
          "remark_text": {
            "description": "Remark text for journal entries",
            "example": "電車代（東京駅→大阪駅）",
            "type": "string"
          }
        },
        "required": [
          "remark_text"
        ],
        "type": "object"
      },
      "CreateReminderRequest": {
        "properties": {
          "day": {
            "description": "Day of month/week for reminder",
            "example": 25,
            "maximum": 31,
            "minimum": 1,
            "type": "integer"
          },
          "month": {
            "description": "Month for yearly reminders (required for yearly cycle)",
            "example": 4,
            "maximum": 12,
            "minimum": 1,
            "type": "integer"
          },
          "reminder_cycle": {
            "$ref": "#/components/schemas/ReminderCycle"
          },
          "reminder_type": {
            "$ref": "#/components/schemas/ReminderType"
          },
          "title": {
            "description": "Reminder title or description",
            "example": "Monthly office rent payment",
            "maxLength": 255,
            "type": "string"
          },
          "week_day": {
            "description": "Day of week for weekly reminders (0=Sunday, 6=Saturday)",
            "example": 1,
            "maximum": 6,
            "minimum": 0,
            "type": "integer"
          },
          "year": {
            "description": "Specific year for one-time reminders",
            "example": 2024,
            "maximum": 2099,
            "minimum": 2020,
            "type": "integer"
          }
        },
        "required": [
          "title",
          "reminder_cycle",
          "reminder_type",
          "day"
        ],
        "type": "object"
      },
      "CreateSalesInvoiceRequest": {
        "properties": {
          "client_id": {
            "description": "Client identifier",
            "format": "uuid",
            "type": "string"
          },
          "document_id": {
            "description": "Associated document identifier",
            "format": "uuid",
            "type": "string"
          },
          "due_date": {
            "description": "Due date as Unix timestamp",
            "example": 1643673600,
            "type": "integer"
          },
          "invoice_number": {
            "description": "Invoice number (optional, auto-generated if not provided)",
            "example": "INV-2024-001",
            "type": "string"
          },
          "issue_date": {
            "description": "Issue date as Unix timestamp",
            "example": 1640995200,
            "type": "integer"
          },
          "items": {
            "description": "Invoice line items",
            "items": {
              "$ref": "#/components/schemas/InvoiceItem"
            },
            "type": "array"
          },
          "notes": {
            "description": "Additional notes",
            "example": [
              "Payment due within 30 days",
              "Late payment fee may apply"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "order_number": {
            "description": "Related order number",
            "example": "ORD-2024-001",
            "type": "string"
          },
          "payment_info": {
            "additionalProperties": true,
            "description": "Payment information",
            "example": {
              "accountName": "ヤマダ タロウ",
              "accountNumber": "1234567",
              "accountType": "普通",
              "bankName": "みずほ銀行",
              "branchName": "東京営業部"
            },
            "type": "object"
          },
          "period_end": {
            "description": "Project period end as Unix timestamp",
            "example": 1643673600,
            "type": "integer"
          },
          "period_start": {
            "description": "Project period start as Unix timestamp",
            "example": 1640995200,
            "type": "integer"
          },
          "project_title": {
            "description": "Project title or description",
            "example": "E-commerce Website Development",
            "type": "string"
          },
          "quote_number": {
            "description": "Related quote number",
            "example": "QUO-2024-001",
            "type": "string"
          },
          "subtotal": {
            "description": "Subtotal amount before tax",
            "example": 200000,
            "minimum": 0,
            "type": "number"
          },
          "tax": {
            "description": "Tax amount",
            "example": 20000,
            "minimum": 0,
            "type": "number"
          },
          "total": {
            "description": "Total amount including tax",
            "example": 220000,
            "minimum": 0,
            "type": "number"
          }
        },
        "required": [
          "document_id",
          "issue_date",
          "due_date",
          "project_title",
          "client_id",
          "subtotal",
          "tax",
          "total",
          "items"
        ],
        "type": "object"
      },
      "CreateSessionRequest": {
        "properties": {
          "companyId": {
            "description": "Associated company ID",
            "format": "uuid",
            "type": "string"
          },
          "dataSource": {
            "$ref": "#/components/schemas/SimulationDataSource"
          },
          "description": {
            "description": "Session description",
            "type": "string"
          },
          "financialData": {
            "description": "Initial financial data state",
            "type": "object"
          },
          "fiscalYear": {
            "example": "2025年度",
            "type": "string"
          },
          "name": {
            "description": "Session name",
            "example": "FY2026 シミュレーション",
            "type": "string"
          },
          "templateId": {
            "description": "Template to load from",
            "format": "uuid",
            "type": "string"
          }
        },
        "type": "object"
      },
      "CreateWithholdingTaxRequest": {
        "properties": {
          "category": {
            "$ref": "#/components/schemas/WithholdingCategory"
          },
          "description": {
            "description": "Payment description",
            "example": "Freelance web development services",
            "type": "string"
          },
          "employee_id": {
            "description": "employees.id of the payee (BL-219); must belong to the caller. Keys the 法定調書 preview and 源泉徴収票 by person instead of by name. 404 when the employee is not found.",
            "format": "uuid",
            "type": "string"
          },
          "gross_amount": {
            "description": "Gross payment amount in JPY",
            "example": 500000,
            "minimum": 0,
            "type": "number"
          },
          "journal_entry_line_id": {
            "description": "Related journal entry line ID",
            "format": "uuid",
            "type": "string"
          },
          "payee_address": {
            "description": "Payee address",
            "example": "東京都渋谷区1-1-1",
            "type": "string"
          },
          "payee_name": {
            "description": "Name of the payee",
            "example": "田中太郎",
            "minLength": 1,
            "type": "string"
          },
          "payee_type": {
            "$ref": "#/components/schemas/PayeeType"
          },
          "payment_date": {
            "description": "Payment date in YYYYMMDD format",
            "example": 20240315,
            "type": "integer"
          },
          "withholding_rate": {
            "description": "Optional custom withholding rate (decimal)",
            "example": 0.1021,
            "maximum": 1,
            "minimum": 0,
            "type": "number"
          }
        },
        "required": [
          "payee_name",
          "payee_type",
          "payment_date",
          "gross_amount",
          "category"
        ],
        "type": "object"
      },
      "CreditCardListResponse": {
        "properties": {
          "data": {
            "properties": {
              "cards": {
                "items": {
                  "$ref": "#/components/schemas/RegisteredCreditCard"
                },
                "type": "array"
              },
              "pagination": {
                "properties": {
                  "hasMore": {
                    "example": false,
                    "type": "boolean"
                  },
                  "limit": {
                    "example": 20,
                    "type": "integer"
                  },
                  "offset": {
                    "example": 0,
                    "type": "integer"
                  },
                  "total": {
                    "example": 5,
                    "type": "integer"
                  }
                },
                "type": "object"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Credit cards retrieved successfully",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "type": "object"
      },
      "CronConfiguration": {
        "properties": {
          "autoStart": {
            "description": "Whether jobs auto-start on application startup",
            "example": true,
            "type": "boolean"
          },
          "cronSecret": {
            "description": "Cron secret configuration status",
            "enum": [
              "configured",
              "not configured"
            ],
            "example": "configured",
            "type": "string"
          },
          "environment": {
            "description": "Current environment (development, staging, production)",
            "enum": [
              "development",
              "staging",
              "production"
            ],
            "example": "development",
            "type": "string"
          },
          "isServerless": {
            "description": "Whether running in serverless environment",
            "example": false,
            "type": "boolean"
          },
          "jobsEnabled": {
            "description": "Individual job enable/disable status",
            "properties": {
              "DEPRECIATION": {
                "example": true,
                "type": "boolean"
              },
              "EXCHANGE_RATE": {
                "example": true,
                "type": "boolean"
              },
              "TRIAL_BALANCE": {
                "example": true,
                "type": "boolean"
              }
            },
            "type": "object"
          },
          "timezone": {
            "description": "Timezone for job scheduling",
            "example": "Asia/Tokyo",
            "type": "string"
          }
        },
        "required": [
          "isServerless",
          "environment",
          "timezone",
          "autoStart",
          "jobsEnabled",
          "cronSecret"
        ],
        "type": "object"
      },
      "CronJobInfo": {
        "properties": {
          "description": {
            "description": "Human-readable job description",
            "example": "Daily exchange rate fetching job",
            "type": "string"
          },
          "enabled": {
            "description": "Whether the job is enabled for execution",
            "example": true,
            "type": "boolean"
          },
          "name": {
            "description": "Cron job name identifier",
            "example": "exchange-rate",
            "type": "string"
          },
          "schedule": {
            "description": "Cron schedule expression with timezone",
            "example": "0 4 * * * (4:00 AM JST)",
            "type": "string"
          }
        },
        "required": [
          "name",
          "description",
          "schedule",
          "enabled"
        ],
        "type": "object"
      },
      "CronLogEntry": {
        "properties": {
          "duration": {
            "description": "Execution duration in milliseconds",
            "example": 330000,
            "minimum": 0,
            "type": "integer"
          },
          "endTime": {
            "description": "Execution end timestamp",
            "example": "2024-01-15T02:05:30.000Z",
            "format": "date-time",
            "type": "string"
          },
          "errors": {
            "description": "Errors encountered during execution",
            "example": [],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "executionType": {
            "description": "Type of execution (scheduled or manual)",
            "enum": [
              "scheduled",
              "manual"
            ],
            "example": "manual",
            "type": "string"
          },
          "id": {
            "description": "Log entry unique identifier",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "jobName": {
            "description": "Name of the cron job",
            "example": "depreciation",
            "type": "string"
          },
          "recordsProcessed": {
            "description": "Number of records processed",
            "example": 125,
            "minimum": 0,
            "type": "integer"
          },
          "startTime": {
            "description": "Execution start timestamp",
            "example": "2024-01-15T02:00:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "status": {
            "description": "Execution status",
            "enum": [
              "success",
              "failure",
              "partial"
            ],
            "example": "success",
            "type": "string"
          },
          "triggeredBy": {
            "description": "User who triggered manual execution",
            "example": "abc12345-def6-7890-ghij-klmnopqrstuv",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          }
        },
        "required": [
          "id",
          "jobName",
          "executionType",
          "status",
          "startTime",
          "endTime",
          "duration",
          "recordsProcessed",
          "errors"
        ],
        "type": "object"
      },
      "CronLogsResponse": {
        "properties": {
          "data": {
            "items": {
              "$ref": "#/components/schemas/CronLogEntry"
            },
            "type": "array"
          },
          "message": {
            "example": "Cron logs retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "CronStatusResponse": {
        "properties": {
          "data": {
            "properties": {
              "availableJobs": {
                "items": {
                  "$ref": "#/components/schemas/CronJobInfo"
                },
                "type": "array"
              },
              "configuration": {
                "$ref": "#/components/schemas/CronConfiguration"
              },
              "manualTriggers": {
                "$ref": "#/components/schemas/ManualTriggerInfo"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Cron status retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "CurrencyRateHistory": {
        "properties": {
          "currency_pair": {
            "description": "Currency pair in FROM/TO format",
            "example": "USD/JPY",
            "type": "string"
          },
          "date_range": {
            "properties": {
              "end_date": {
                "description": "End date of the range",
                "example": 20240131,
                "type": "integer"
              },
              "start_date": {
                "description": "Start date of the range",
                "example": 20240101,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "from_currency": {
            "description": "Source currency code",
            "example": "USD",
            "type": "string"
          },
          "rates": {
            "description": "Historical rates for this currency pair",
            "items": {
              "properties": {
                "date": {
                  "description": "Rate date in YYYYMMDD format",
                  "example": 20240115,
                  "type": "integer"
                },
                "rate": {
                  "description": "Exchange rate for this date",
                  "example": 150.25,
                  "format": "decimal",
                  "type": "number"
                },
                "source": {
                  "description": "Source of the rate",
                  "example": "external_api",
                  "type": "string"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "to_currency": {
            "description": "Target currency code",
            "example": "JPY",
            "type": "string"
          }
        },
        "required": [
          "currency_pair",
          "from_currency",
          "to_currency",
          "rates",
          "date_range"
        ],
        "type": "object"
      },
      "CurrencyRatesResponse": {
        "properties": {
          "data": {
            "items": {
              "$ref": "#/components/schemas/CurrencyRateHistory"
            },
            "type": "array"
          },
          "message": {
            "example": "Currency rates retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "DailyMetricsResponse": {
        "properties": {
          "items": {
            "items": {
              "properties": {
                "count_observations": {
                  "example": 120,
                  "type": "integer"
                },
                "count_traces": {
                  "example": 45,
                  "type": "integer"
                },
                "date": {
                  "example": "2026-03-06",
                  "type": "string"
                },
                "total_cost": {
                  "example": 1.23,
                  "type": "number"
                },
                "usage": {
                  "items": {
                    "properties": {
                      "input_usage": {
                        "example": 5000,
                        "type": "integer"
                      },
                      "model": {
                        "example": "gpt-4o",
                        "type": "string"
                      },
                      "output_usage": {
                        "example": 2000,
                        "type": "integer"
                      },
                      "total_cost": {
                        "example": 0.45,
                        "type": "number"
                      },
                      "total_usage": {
                        "example": 7000,
                        "type": "integer"
                      }
                    },
                    "type": "object"
                  },
                  "type": "array"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "source": {
            "enum": [
              "langfuse",
              "local"
            ],
            "example": "langfuse",
            "type": "string"
          }
        },
        "required": [
          "items",
          "source"
        ],
        "type": "object"
      },
      "DashboardResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/ComplianceDashboard"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "DataIntegrityHealth": {
        "properties": {
          "healthScore": {
            "description": "Overall data integrity score (0-100)",
            "example": 98.5,
            "maximum": 100,
            "minimum": 0,
            "type": "number"
          },
          "missingDocuments": {
            "description": "Number of entries with missing reference documents",
            "example": 2,
            "type": "integer"
          },
          "orphanEntries": {
            "description": "Number of journal entries without lines",
            "example": 0,
            "type": "integer"
          },
          "recommendations": {
            "description": "Recommended actions for data integrity improvement",
            "example": [
              "Review entries with missing documents",
              "Run monthly integrity check"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "unbalancedEntries": {
            "description": "Number of entries where debit ≠ credit",
            "example": 0,
            "type": "integer"
          }
        },
        "required": [
          "orphanEntries",
          "unbalancedEntries",
          "missingDocuments",
          "healthScore",
          "recommendations"
        ],
        "type": "object"
      },
      "DataIntegrityResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/DataIntegrityHealth"
          },
          "message": {
            "example": "Data integrity health check completed",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "DatabaseDocsResponse": {
        "properties": {
          "data": {
            "properties": {
              "enums": {
                "description": "Database enums",
                "items": {
                  "$ref": "#/components/schemas/DatabaseEnum"
                },
                "type": "array"
              },
              "envVariables": {
                "description": "Environment variables configuration",
                "type": "object"
              },
              "models": {
                "description": "All database models",
                "items": {
                  "$ref": "#/components/schemas/DatabaseModel"
                },
                "type": "array"
              },
              "modelsByCategory": {
                "additionalProperties": {
                  "items": {
                    "$ref": "#/components/schemas/DatabaseModel"
                  },
                  "type": "array"
                },
                "description": "Models grouped by category",
                "type": "object"
              },
              "stats": {
                "$ref": "#/components/schemas/DatabaseStats"
              },
              "supabaseConfig": {
                "description": "Supabase configuration",
                "items": {
                  "$ref": "#/components/schemas/SupabaseConfig"
                },
                "type": "array"
              }
            },
            "required": [
              "models",
              "modelsByCategory",
              "enums",
              "supabaseConfig",
              "envVariables",
              "stats"
            ],
            "type": "object"
          },
          "message": {
            "example": "Database documentation retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "DatabaseEnum": {
        "properties": {
          "description": {
            "description": "Enum description",
            "example": "Document status values",
            "type": "string"
          },
          "name": {
            "description": "Enum name",
            "example": "document_status",
            "type": "string"
          },
          "values": {
            "description": "Enum values",
            "example": [
              "DRAFT",
              "PUBLISHED",
              "ARCHIVED"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          }
        },
        "required": [
          "name",
          "values",
          "description"
        ],
        "type": "object"
      },
      "DatabaseEnumsResponse": {
        "properties": {
          "data": {
            "description": "Database enums",
            "items": {
              "$ref": "#/components/schemas/DatabaseEnum"
            },
            "type": "array"
          },
          "message": {
            "example": "Database enums retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "DatabaseModel": {
        "properties": {
          "category": {
            "description": "Business category",
            "example": "Core",
            "type": "string"
          },
          "description": {
            "description": "Model description",
            "example": "User accounts with preferences and authentication data",
            "type": "string"
          },
          "displayName": {
            "description": "Human-readable model name",
            "example": "User Profiles",
            "type": "string"
          },
          "fields": {
            "description": "Model fields",
            "items": {
              "$ref": "#/components/schemas/ModelField"
            },
            "type": "array"
          },
          "indexes": {
            "description": "Database indexes",
            "items": {
              "type": "string"
            },
            "nullable": true,
            "type": "array"
          },
          "name": {
            "description": "Model table name",
            "example": "user_profiles",
            "type": "string"
          },
          "relations": {
            "description": "Model relations",
            "items": {
              "$ref": "#/components/schemas/ModelRelation"
            },
            "type": "array"
          }
        },
        "required": [
          "name",
          "displayName",
          "description",
          "category",
          "fields",
          "relations"
        ],
        "type": "object"
      },
      "DatabaseModelsResponse": {
        "properties": {
          "data": {
            "description": "All database models",
            "items": {
              "$ref": "#/components/schemas/DatabaseModel"
            },
            "type": "array"
          },
          "message": {
            "example": "Database models retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "DatabaseStats": {
        "properties": {
          "categories": {
            "description": "Available model categories",
            "example": [
              "Core",
              "Business",
              "System"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "totalEnums": {
            "description": "Total number of enums",
            "example": 8,
            "type": "number"
          },
          "totalFields": {
            "description": "Total number of fields across all models",
            "example": 120,
            "type": "number"
          },
          "totalModels": {
            "description": "Total number of models",
            "example": 15,
            "type": "number"
          },
          "totalRelations": {
            "description": "Total number of relations",
            "example": 45,
            "type": "number"
          }
        },
        "required": [
          "totalModels",
          "totalEnums",
          "totalFields",
          "totalRelations",
          "categories"
        ],
        "type": "object"
      },
      "DatabaseStatsResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/DatabaseStats"
          },
          "message": {
            "example": "Database statistics retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "DateFormat": {
        "description": "Date in YYYYMMDD format for Japanese business standards",
        "example": "20241231",
        "pattern": "^\\d{8}$",
        "type": "string"
      },
      "DateRange": {
        "properties": {
          "from": {
            "description": "Start date",
            "example": "2024-01-01",
            "format": "date",
            "type": "string"
          },
          "to": {
            "description": "End date",
            "example": "2024-03-31",
            "format": "date",
            "type": "string"
          }
        },
        "required": [
          "from",
          "to"
        ],
        "type": "object"
      },
      "DateRangeFetchJob": {
        "properties": {
          "created_at": {
            "description": "Job creation timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "date_range": {
            "properties": {
              "end_date": {
                "description": "End date in YYYYMMDD format",
                "example": 20240131,
                "type": "integer"
              },
              "start_date": {
                "description": "Start date in YYYYMMDD format",
                "example": 20240101,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "estimated_completion": {
            "description": "Estimated completion time",
            "example": "2024-01-15T11:00:00.000Z",
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "force_refresh": {
            "description": "Whether to force refresh existing rates",
            "example": false,
            "type": "boolean"
          },
          "job_id": {
            "description": "Background job identifier",
            "example": "789e0123-e45b-67c8-d901-234567890123",
            "format": "uuid",
            "type": "string"
          },
          "processed_days": {
            "description": "Number of days already processed",
            "example": 0,
            "minimum": 0,
            "type": "integer"
          },
          "status": {
            "description": "Job processing status",
            "enum": [
              "queued",
              "processing",
              "completed",
              "failed"
            ],
            "example": "queued",
            "type": "string"
          },
          "total_days": {
            "description": "Total number of days to process",
            "example": 31,
            "minimum": 1,
            "type": "integer"
          }
        },
        "required": [
          "job_id",
          "status",
          "date_range",
          "total_days",
          "processed_days",
          "force_refresh",
          "created_at"
        ],
        "type": "object"
      },
      "DateRangeFetchResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/DateRangeFetchJob"
          },
          "message": {
            "example": "Date range fetch job created successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 202,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "DeadlineFilingRecord": {
        "properties": {
          "completedAt": {
            "nullable": true,
            "type": "string"
          },
          "completionSource": {
            "description": "'manual' (the owner), 'engine' (a quarter the 消費税 schedule shows submitted) or 'register' (源泉 the 源泉徴収 register shows paid and bank-linked)",
            "nullable": true,
            "type": "string"
          },
          "evidenceFileId": {
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "evidenceFileName": {
            "nullable": true,
            "type": "string"
          },
          "filedMonth": {
            "description": "YYYY-MM (「7月頃」).",
            "example": "2026-07",
            "nullable": true,
            "type": "string"
          },
          "filedOn": {
            "description": "The owner’s date, or the e-Tax transmission day of an engine-completed 消費税 quarter.",
            "format": "date",
            "nullable": true,
            "type": "string"
          },
          "filedOnUnknown": {
            "description": "「提出日が不明」 — filedOn is null; filedMonth when known.",
            "type": "boolean"
          },
          "filingMethod": {
            "description": "提出方法; null on records made before it was asked.",
            "enum": [
              "eltax",
              "etax",
              "mail",
              "counter",
              "other",
              null
            ],
            "nullable": true,
            "type": "string"
          },
          "paidOn": {
            "description": "When 「納付しました」 closed a row that was filed first; filedOn stays the filing date.",
            "format": "date",
            "nullable": true,
            "type": "string"
          },
          "paymentPending": {
            "description": "Filed (「提出しました」) while the payment is still owed: the row stays open and reminds until 「納付しました」.",
            "type": "boolean"
          },
          "receiptNumber": {
            "nullable": true,
            "type": "string"
          },
          "trackingNumber": {
            "description": "簡易書留・特定記録の追跡番号 (郵送).",
            "nullable": true,
            "type": "string"
          },
          "undoable": {
            "type": "boolean"
          }
        },
        "required": [
          "filedOn",
          "filedOnUnknown",
          "filedMonth",
          "filingMethod",
          "receiptNumber",
          "trackingNumber",
          "evidenceFileId",
          "evidenceFileName",
          "completedAt",
          "completionSource",
          "undoable",
          "paymentPending",
          "paidOn"
        ],
        "type": "object"
      },
      "DeadlineObject": {
        "properties": {
          "amount_estimated": {
            "description": "amount_yen is SBC’s estimate (見込) for at least one payee — no 納付書 is saved for it.",
            "type": "boolean"
          },
          "amount_is_estimate": {
            "description": "The amount still owed rests on an estimate (no saved 納付書 or 告知書 for an unpaid payment): the list prints 見込 beside it.",
            "type": "boolean"
          },
          "amount_note": {
            "description": "How amount_yen was reached, when the row should say so beside it (a new office’s 均等割: 「事業所を設けた月数（1か月）で計算」).",
            "example": "事業所を設けた月数（1か月）で計算",
            "nullable": true,
            "type": "string"
          },
          "amount_yen": {
            "description": "What the owner still pays for this row (interim taxes): each unpaid payment at its saved 納付書 amount, else the estimate from the prior filed return; 0 when the bank shows every payment paid; null when the row has no payments.",
            "example": 1464500,
            "nullable": true,
            "type": "integer"
          },
          "carried_over": {
            "description": "The owner’s 完了 was carried here from a superseded row of the same obligation (same rule, same 事業年度 window) — 「旧表示の行から引き継いだ完了記録です」. It can be taken back like any 完了.",
            "type": "boolean"
          },
          "completed_at": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "created_at": {
            "format": "date-time",
            "type": "string"
          },
          "description_ja": {
            "nullable": true,
            "type": "string"
          },
          "due_date": {
            "format": "date",
            "type": "string"
          },
          "engine_version": {
            "example": "deadline@1.0.0",
            "type": "string"
          },
          "filed_month": {
            "description": "YYYY-MM with filed_on_unknown (「7月頃」).",
            "nullable": true,
            "type": "string"
          },
          "filed_on": {
            "description": "Filed date the owner recorded.",
            "format": "date",
            "nullable": true,
            "type": "string"
          },
          "filed_on_unknown": {
            "description": "「提出日が不明」 recorded — filed_on is null.",
            "type": "boolean"
          },
          "filing_method": {
            "description": "提出方法 (eLTAX / e-Tax / 郵送 / 窓口 / その他).",
            "enum": [
              "eltax",
              "etax",
              "mail",
              "counter",
              "other",
              null
            ],
            "nullable": true,
            "type": "string"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "legal_basis": {
            "nullable": true,
            "type": "string"
          },
          "payment_pending": {
            "description": "Filed while the payment is still owed: an open row that carries filed_on / receipt_number.",
            "type": "boolean"
          },
          "payment_progress": {
            "description": "Payments the bank shows as paid, of all payments of the row; null when the row has no payments.",
            "nullable": true,
            "properties": {
              "paid": {
                "example": 1,
                "type": "integer"
              },
              "total": {
                "example": 2,
                "type": "integer"
              }
            },
            "required": [
              "paid",
              "total"
            ],
            "type": "object"
          },
          "period_label": {
            "example": "2025_annual",
            "type": "string"
          },
          "prep": {
            "description": "SBC's 目安 to start the work (not a legal date): the day of the rule's first prepare-stage reminder (p<n>) when it has one, else a fixed number of months before the due date.",
            "nullable": true,
            "properties": {
              "date": {
                "example": "2026-12-15",
                "format": "date",
                "type": "string"
              },
              "label": {
                "example": "Q3の帳簿を締める目安",
                "type": "string"
              }
            },
            "required": [
              "date",
              "label"
            ],
            "type": "object"
          },
          "read_only": {
            "description": "A row of the election / lock-in register (BE ADR-0023): いつから選べるか, nothing to file. complete and dismiss are refused with 409; reopen stays open for a row recorded earlier.",
            "type": "boolean"
          },
          "receipt_number": {
            "description": "受付番号 recorded with the filing.",
            "nullable": true,
            "type": "string"
          },
          "rule_key": {
            "example": "corporate_tax_filing",
            "type": "string"
          },
          "source_module": {
            "example": "deadline_engine",
            "type": "string"
          },
          "status": {
            "enum": [
              "upcoming",
              "due_soon",
              "overdue",
              "completed",
              "not_applicable",
              "dismissed",
              "closed"
            ],
            "type": "string"
          },
          "superseded": {
            "description": "Dated by an earlier, wrong 事業年度 pick and replaced by a relabelled row: kept as a record (履歴・旧表示), never changed again. Such rows come back only with include_superseded=true.",
            "type": "boolean"
          },
          "tracking_number": {
            "description": "簡易書留・特定記録の追跡番号 (郵送).",
            "nullable": true,
            "type": "string"
          },
          "undoable": {
            "description": "The completion or dismissal can be taken back (false for an engine-completed quarter).",
            "type": "boolean"
          },
          "updated_at": {
            "format": "date-time",
            "type": "string"
          },
          "why_line": {
            "description": "Why this obligation applies to this company, in plain Japanese (rendered from the row inputs).",
            "example": "7月1日の時点で社会保険に入っている人（役員を含む）がいるため、毎年提出します。",
            "type": "string"
          }
        },
        "type": "object"
      },
      "DeductionCategory": {
        "properties": {
          "category": {
            "description": "Deduction category name",
            "example": "本人に関する控除",
            "type": "string"
          },
          "items": {
            "description": "Deduction items in this category",
            "items": {
              "$ref": "#/components/schemas/DeductionItem"
            },
            "type": "array"
          }
        },
        "required": [
          "category",
          "items"
        ],
        "type": "object"
      },
      "DeductionChecklistResponse": {
        "properties": {
          "data": {
            "properties": {
              "checklist": {
                "items": {
                  "$ref": "#/components/schemas/DeductionCategory"
                },
                "type": "array"
              },
              "deadlines": {
                "properties": {
                  "calculation": {
                    "example": "翌年1月10日まで（納付期限）",
                    "type": "string"
                  },
                  "documentSubmission": {
                    "example": "12月の給与支給日まで",
                    "type": "string"
                  },
                  "withholdingSlipIssue": {
                    "example": "翌年1月31日まで",
                    "type": "string"
                  }
                },
                "type": "object"
              },
              "notes": {
                "example": [
                  "中途入社の場合、前職の源泉徴収票が必要",
                  "退職者は退職時に年末調整を行う",
                  "年収2,000万円超の従業員は確定申告が必要"
                ],
                "items": {
                  "type": "string"
                },
                "type": "array"
              }
            },
            "type": "object"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "DeductionConfig": {
        "description": "Annual deduction configuration (年度別控除設定)",
        "properties": {
          "deductions": {
            "properties": {
              "basic": {
                "description": "基礎控除",
                "properties": {
                  "name": {
                    "example": "基礎控除",
                    "type": "string"
                  },
                  "tiers": {
                    "items": {
                      "properties": {
                        "amount": {
                          "example": 950000,
                          "type": "integer"
                        },
                        "incomeMax": {
                          "example": 1320000,
                          "nullable": true,
                          "type": "integer"
                        }
                      },
                      "type": "object"
                    },
                    "type": "array"
                  }
                },
                "type": "object"
              },
              "dependent": {
                "description": "扶養控除",
                "properties": {
                  "amounts": {
                    "properties": {
                      "elderly": {
                        "example": 480000,
                        "type": "integer"
                      },
                      "elderlyLivingTogether": {
                        "example": 580000,
                        "type": "integer"
                      },
                      "general": {
                        "example": 380000,
                        "type": "integer"
                      },
                      "specific": {
                        "example": 630000,
                        "type": "integer"
                      }
                    },
                    "type": "object"
                  },
                  "incomeLimit": {
                    "example": 580000,
                    "type": "integer"
                  },
                  "name": {
                    "example": "扶養控除",
                    "type": "string"
                  }
                },
                "type": "object"
              },
              "employmentIncome": {
                "description": "給与所得控除",
                "properties": {
                  "minimum": {
                    "example": 650000,
                    "type": "integer"
                  },
                  "name": {
                    "example": "給与所得控除",
                    "type": "string"
                  },
                  "tiers": {
                    "items": {
                      "type": "object"
                    },
                    "type": "array"
                  }
                },
                "type": "object"
              }
            },
            "type": "object"
          },
          "japaneseYear": {
            "example": "令和7年",
            "type": "string"
          },
          "taxReformApplied": {
            "example": "令和7年度税制改正",
            "nullable": true,
            "type": "string"
          },
          "year": {
            "example": 2025,
            "type": "integer"
          }
        },
        "type": "object"
      },
      "DeductionItem": {
        "properties": {
          "description": {
            "description": "Deduction description",
            "example": "全員に適用（所得2,400万円以下で48万円）",
            "type": "string"
          },
          "maxAmount": {
            "description": "Maximum deduction amount (optional)",
            "example": 480000,
            "format": "decimal",
            "type": "number"
          },
          "name": {
            "description": "Deduction item name (English)",
            "example": "basicDeduction",
            "type": "string"
          },
          "nameJa": {
            "description": "Deduction item name (Japanese)",
            "example": "基礎控除",
            "type": "string"
          },
          "requiredDocuments": {
            "description": "Required documents for this deduction",
            "example": [
              "不要（自動適用）"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          }
        },
        "required": [
          "name",
          "nameJa",
          "description",
          "requiredDocuments"
        ],
        "type": "object"
      },
      "DeleteClientParams": {
        "properties": {
          "client_id": {
            "description": "Unique identifier of the client to delete",
            "example": "550e8400-e29b-41d4-a716-446655440000",
            "format": "uuid",
            "type": "string"
          }
        },
        "required": [
          "client_id"
        ],
        "type": "object"
      },
      "DeleteClientSuccessResponse": {
        "properties": {
          "message": {
            "example": "Client deleted successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message"
        ],
        "type": "object"
      },
      "DeleteDocumentResponse": {
        "properties": {
          "data": {
            "properties": {
              "deletedAt": {
                "format": "date-time",
                "type": "string"
              },
              "deletedBy": {
                "format": "uuid",
                "type": "string"
              },
              "id": {
                "format": "uuid",
                "type": "string"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Document deleted successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "type": "object"
      },
      "DeleteFilesRequest": {
        "properties": {
          "file_ids": {
            "description": "Array of file IDs to delete (at least one required)",
            "example": [
              "123e4567-e89b-12d3-a456-426614174000",
              "789e0123-e45b-67c8-d901-234567890123"
            ],
            "items": {
              "format": "uuid",
              "type": "string"
            },
            "minItems": 1,
            "type": "array"
          }
        },
        "required": [
          "file_ids"
        ],
        "type": "object"
      },
      "DeleteWithholdingResponse": {
        "properties": {
          "data": {
            "properties": {
              "deleted": {
                "example": true,
                "type": "boolean"
              },
              "hardDelete": {
                "example": false,
                "type": "boolean"
              },
              "status": {
                "example": "cancelled",
                "type": "string"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "源泉徴収レコードをキャンセルしました",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "DemoDataStats": {
        "properties": {
          "bank_statements": {
            "description": "Number of demo bank statements",
            "example": 25,
            "type": "integer"
          },
          "clients": {
            "description": "Number of demo clients",
            "example": 8,
            "type": "integer"
          },
          "companies": {
            "description": "Number of demo companies",
            "example": 1,
            "type": "integer"
          },
          "documents": {
            "description": "Number of demo documents",
            "example": 45,
            "type": "integer"
          },
          "journal_entries": {
            "description": "Number of demo journal entries",
            "example": 150,
            "type": "integer"
          },
          "pay_slips": {
            "description": "Number of demo pay slips",
            "example": 12,
            "type": "integer"
          },
          "sales_invoices": {
            "description": "Number of demo sales invoices",
            "example": 30,
            "type": "integer"
          }
        },
        "required": [
          "bank_statements",
          "clients",
          "journal_entries",
          "documents",
          "pay_slips",
          "sales_invoices",
          "companies"
        ],
        "type": "object"
      },
      "DemoErrorResponse": {
        "properties": {
          "code": {
            "description": "Error code for programmatic handling",
            "enum": [
              "DEMO_MGMT_DISABLED",
              "INVALID_ADMIN_TOKEN",
              "DEMO_STATUS_ERROR",
              "DEMO_RESET_ERROR",
              "DEMO_VALIDATION_ERROR"
            ],
            "example": "DEMO_MGMT_DISABLED",
            "type": "string"
          },
          "error": {
            "description": "Error message",
            "example": "Demo management not configured",
            "type": "string"
          }
        },
        "required": [
          "error",
          "code"
        ],
        "type": "object"
      },
      "DemoProcessingRun": {
        "properties": {
          "companyId": {
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "completedAt": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "createdAt": {
            "format": "date-time",
            "type": "string"
          },
          "documentsGenerated": {
            "items": {
              "type": "object"
            },
            "type": "array"
          },
          "durationMs": {
            "nullable": true,
            "type": "integer"
          },
          "errors": {
            "items": {
              "type": "object"
            },
            "type": "array"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "journalEntryCount": {
            "type": "integer"
          },
          "sessionId": {
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "sourceFileName": {
            "nullable": true,
            "type": "string"
          },
          "sourceType": {
            "$ref": "#/components/schemas/DemoProcessingSourceType"
          },
          "startedAt": {
            "format": "date-time",
            "type": "string"
          },
          "success": {
            "type": "boolean"
          },
          "userId": {
            "format": "uuid",
            "type": "string"
          },
          "warnings": {
            "items": {
              "type": "object"
            },
            "type": "array"
          }
        },
        "type": "object"
      },
      "DemoProcessingSourceType": {
        "description": "Source type of processing data",
        "enum": [
          "uploaded",
          "backend",
          "mock"
        ],
        "example": "mock",
        "type": "string"
      },
      "DemoResetResponse": {
        "properties": {
          "deletedCounts": {
            "description": "Count of deleted records by entity type",
            "properties": {
              "bank_statements": {
                "example": 25,
                "type": "integer"
              },
              "clients": {
                "example": 8,
                "type": "integer"
              },
              "companies": {
                "example": 1,
                "type": "integer"
              },
              "documents": {
                "example": 45,
                "type": "integer"
              },
              "general_ledger_lines": {
                "example": 300,
                "type": "integer"
              },
              "journal_entries": {
                "example": 150,
                "type": "integer"
              },
              "pay_slips": {
                "example": 12,
                "type": "integer"
              },
              "reconciliation_rules": {
                "example": 5,
                "type": "integer"
              },
              "sales_invoices": {
                "example": 30,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "durationMs": {
            "description": "Reset operation duration in milliseconds",
            "example": 2500,
            "type": "integer"
          },
          "message": {
            "description": "Success message",
            "example": "Demo data reset completed",
            "type": "string"
          },
          "success": {
            "description": "Whether the reset operation succeeded",
            "example": true,
            "type": "boolean"
          },
          "timestamp": {
            "description": "Reset operation timestamp",
            "example": "2024-03-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          }
        },
        "required": [
          "message",
          "success",
          "deletedCounts",
          "timestamp",
          "durationMs"
        ],
        "type": "object"
      },
      "DemoResetResult": {
        "properties": {
          "deletedCounts": {
            "description": "Count of deleted records by entity type",
            "properties": {
              "bank_statements": {
                "description": "Number of bank statements deleted",
                "example": 25,
                "type": "integer"
              },
              "clients": {
                "description": "Number of clients deleted",
                "example": 8,
                "type": "integer"
              },
              "companies": {
                "description": "Number of companies deleted",
                "example": 1,
                "type": "integer"
              },
              "documents": {
                "description": "Number of documents deleted",
                "example": 45,
                "type": "integer"
              },
              "general_ledger_lines": {
                "description": "Number of general ledger lines deleted",
                "example": 300,
                "type": "integer"
              },
              "journal_entries": {
                "description": "Number of journal entries deleted",
                "example": 150,
                "type": "integer"
              },
              "pay_slips": {
                "description": "Number of pay slips deleted",
                "example": 12,
                "type": "integer"
              },
              "reconciliation_rules": {
                "description": "Number of reconciliation rules deleted",
                "example": 5,
                "type": "integer"
              },
              "sales_invoices": {
                "description": "Number of sales invoices deleted",
                "example": 30,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "durationMs": {
            "description": "Reset operation duration in milliseconds",
            "example": 2500,
            "type": "integer"
          },
          "success": {
            "description": "Whether the reset operation succeeded",
            "example": true,
            "type": "boolean"
          },
          "timestamp": {
            "description": "Reset operation timestamp",
            "example": "2024-03-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          }
        },
        "required": [
          "success",
          "deletedCounts",
          "timestamp",
          "durationMs"
        ],
        "type": "object"
      },
      "DemoStatusResponse": {
        "properties": {
          "demoUserId": {
            "description": "Demo user ID",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "enabled": {
            "description": "Whether demo mode is enabled",
            "example": true,
            "type": "boolean"
          },
          "isValid": {
            "description": "Whether demo data is valid",
            "example": true,
            "type": "boolean"
          },
          "issues": {
            "description": "List of validation issues",
            "example": [],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "lastReset": {
            "description": "Last reset timestamp (null if never reset)",
            "example": "2024-03-15T10:30:00.000Z",
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "stats": {
            "$ref": "#/components/schemas/DemoDataStats"
          }
        },
        "required": [
          "enabled",
          "demoUserId",
          "lastReset",
          "stats",
          "isValid",
          "issues"
        ],
        "type": "object"
      },
      "DemoValidationResult": {
        "properties": {
          "isValid": {
            "description": "Whether demo data is valid and complete",
            "example": true,
            "type": "boolean"
          },
          "issues": {
            "description": "List of validation issues found",
            "example": [],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "stats": {
            "$ref": "#/components/schemas/DemoDataStats"
          }
        },
        "required": [
          "isValid",
          "issues",
          "stats"
        ],
        "type": "object"
      },
      "DepreciableAssetReturnData": {
        "description": "償却資産申告データ - Assets categorized by tax eligibility",
        "properties": {
          "asOfDate": {
            "description": "賦課期日 (January 1st of filing year)",
            "example": 20260101,
            "type": "integer"
          },
          "exemptAssets": {
            "description": "対象外資産 (with exemption reason)",
            "items": {
              "$ref": "#/components/schemas/ExemptAsset"
            },
            "type": "array"
          },
          "filingYear": {
            "description": "申告年度",
            "example": 2026,
            "type": "integer"
          },
          "reviewRequired": {
            "description": "確認が必要な資産",
            "items": {
              "$ref": "#/components/schemas/ReviewRequiredAsset"
            },
            "type": "array"
          },
          "summary": {
            "$ref": "#/components/schemas/DepreciableAssetReturnSummary"
          },
          "taxableAssets": {
            "description": "申告対象資産",
            "items": {
              "$ref": "#/components/schemas/TaxableAsset"
            },
            "type": "array"
          }
        },
        "type": "object"
      },
      "DepreciableAssetReturnResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/DepreciableAssetReturnData"
          },
          "message": {
            "example": "償却資産申告データを取得しました",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "type": "object"
      },
      "DepreciableAssetReturnSummary": {
        "description": "Summary statistics for 償却資産申告",
        "properties": {
          "byCategory": {
            "additionalProperties": {
              "properties": {
                "count": {
                  "example": 1,
                  "type": "integer"
                },
                "name": {
                  "example": "構築物",
                  "type": "string"
                },
                "value": {
                  "example": 500000,
                  "type": "number"
                }
              },
              "type": "object"
            },
            "description": "Breakdown by 地方税法 category",
            "example": {
              "1": {
                "count": 1,
                "name": "構築物",
                "value": 500000
              },
              "6": {
                "count": 2,
                "name": "工具、器具及び備品",
                "value": 750000
              }
            },
            "type": "object"
          },
          "totalExemptAssets": {
            "description": "対象外資産数",
            "example": 2,
            "type": "integer"
          },
          "totalReviewRequired": {
            "description": "確認が必要な資産数",
            "example": 1,
            "type": "integer"
          },
          "totalTaxableAssets": {
            "description": "申告対象資産数",
            "example": 3,
            "type": "integer"
          },
          "totalTaxableValue": {
            "description": "申告対象評価額合計",
            "example": 1250000,
            "type": "number"
          }
        },
        "type": "object"
      },
      "DepreciableTaxCategory": {
        "description": "地方税法 asset category for 償却資産申告",
        "enum": [
          1,
          2,
          3,
          4,
          5,
          6
        ],
        "type": "integer",
        "x-enum-descriptions": [
          "構築物 (Structures)",
          "機械及び装置 (Machinery and Equipment)",
          "船舶 (Ships)",
          "航空機 (Aircraft)",
          "車両及び運搬具 (Vehicles - excluded, taxed via 自動車税)",
          "工具、器具及び備品 (Tools, Equipment and Fixtures)"
        ],
        "x-enum-varnames": [
          "STRUCTURES",
          "MACHINERY",
          "SHIPS",
          "AIRCRAFT",
          "VEHICLES",
          "TOOLS_EQUIPMENT"
        ]
      },
      "DepreciationMethod": {
        "description": "Japanese depreciation calculation method",
        "enum": [
          1,
          2,
          3,
          4
        ],
        "example": 1,
        "type": "integer",
        "x-enum-descriptions": [
          "定額法 (Straight Line Method)",
          "定率法 (Declining Balance Method)",
          "旧定額法 (Old Straight Line Method)",
          "旧定率法 (Old Declining Balance Method)"
        ],
        "x-enum-varnames": [
          "STRAIGHT_LINE",
          "DECLINING_BALANCE",
          "OLD_STRAIGHT_LINE",
          "OLD_DECLINING_BALANCE"
        ]
      },
      "DetailedHealthResponse": {
        "properties": {
          "checks": {
            "properties": {
              "failed": {
                "example": 0,
                "type": "number"
              },
              "passed": {
                "example": 1,
                "type": "number"
              },
              "total": {
                "example": 1,
                "type": "number"
              }
            },
            "type": "object"
          },
          "components": {
            "properties": {
              "circuitBreakers": {
                "items": {
                  "$ref": "#/components/schemas/CircuitBreakerHealth"
                },
                "type": "array"
              },
              "database": {
                "$ref": "#/components/schemas/ComponentHealth"
              }
            },
            "type": "object"
          },
          "requestId": {
            "format": "uuid",
            "type": "string"
          },
          "status": {
            "description": "Overall system health status",
            "enum": [
              "healthy",
              "degraded",
              "unhealthy"
            ],
            "example": "healthy",
            "type": "string"
          },
          "system": {
            "$ref": "#/components/schemas/SystemMetrics"
          },
          "timestamp": {
            "format": "date-time",
            "type": "string"
          },
          "version": {
            "description": "API version",
            "example": "4.24.0",
            "type": "string"
          }
        },
        "type": "object"
      },
      "DetectTransferRequest": {
        "properties": {
          "date_tolerance_days": {
            "default": 3,
            "description": "Number of days tolerance for matching transfer dates",
            "maximum": 7,
            "minimum": 0,
            "type": "integer"
          },
          "transaction_id": {
            "description": "Bank statement transaction ID to check for matching transfer",
            "format": "uuid",
            "type": "string"
          }
        },
        "required": [
          "transaction_id"
        ],
        "type": "object"
      },
      "DetectTransferResponse": {
        "properties": {
          "data": {
            "properties": {
              "confidence": {
                "enum": [
                  "high",
                  "medium",
                  "low"
                ],
                "type": "string"
              },
              "is_transfer": {
                "example": true,
                "type": "boolean"
              },
              "matching_transaction": {
                "nullable": true,
                "properties": {
                  "amount": {
                    "type": "number"
                  },
                  "bank_account_id": {
                    "format": "uuid",
                    "type": "string"
                  },
                  "description": {
                    "type": "string"
                  },
                  "id": {
                    "format": "uuid",
                    "type": "string"
                  },
                  "transaction_date": {
                    "example": 20260201,
                    "type": "integer"
                  }
                },
                "type": "object"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "振替検出結果",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "type": "object"
      },
      "DeviceInfo": {
        "properties": {
          "browser": {
            "description": "Browser user agent",
            "example": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
            "nullable": true,
            "type": "string"
          },
          "platform": {
            "description": "Device platform",
            "enum": [
              "web",
              "ios",
              "android",
              "desktop"
            ],
            "example": "web",
            "type": "string"
          },
          "version": {
            "description": "App version",
            "example": "1.0.0",
            "nullable": true,
            "type": "string"
          }
        },
        "type": "object"
      },
      "DockHasInkan": {
        "description": "VR-08 (v5.20+). True when the document's content carries a non-empty 印影 image at\n`signature.inkanImage` / `signature.inkan_image` / `companyInfo.inkanImage` / `companyInfo.inkan_image`\n— the FIRST of those keys that is present decides (an empty string therefore means false, it does not fall\nthrough). Before this field the dock fetched each chain document just to read it.",
        "example": true,
        "type": "boolean"
      },
      "DockSummaryResponse": {
        "properties": {
          "data": {
            "properties": {
              "generalLedger": {
                "description": "General ledger summary",
                "properties": {
                  "accountCount": {
                    "description": "Unique accounts with entries",
                    "example": 15,
                    "type": "integer"
                  },
                  "discrepancy": {
                    "example": 0,
                    "type": "integer"
                  },
                  "isBalanced": {
                    "example": true,
                    "type": "boolean"
                  },
                  "totalCredit": {
                    "example": 12345678,
                    "type": "integer"
                  },
                  "totalDebit": {
                    "example": 12345678,
                    "type": "integer"
                  },
                  "transactionCount": {
                    "description": "Posted journal entry lines (matches GL 総取引数)",
                    "example": 48,
                    "type": "integer"
                  }
                },
                "type": "object"
              },
              "journal": {
                "description": "Journal entry summary (posted entries for totals, all statuses for counts)",
                "properties": {
                  "bySourceType": {
                    "description": "Entry count by source category",
                    "properties": {
                      "ai": {
                        "description": "AI-generated entries",
                        "example": 0,
                        "type": "integer"
                      },
                      "bank": {
                        "description": "Bank feed / card statement entries",
                        "example": 49,
                        "type": "integer"
                      },
                      "expense": {
                        "description": "Expense claim / invoice entries",
                        "example": 0,
                        "type": "integer"
                      },
                      "manual": {
                        "description": "Manual / CSV import / adjustment entries",
                        "example": 848,
                        "type": "integer"
                      },
                      "other": {
                        "description": "Payroll, depreciation, opening balance, etc.",
                        "example": 0,
                        "type": "integer"
                      },
                      "recurring": {
                        "description": "Recurring entries",
                        "example": 0,
                        "type": "integer"
                      }
                    },
                    "type": "object"
                  },
                  "discrepancy": {
                    "description": "Debit minus credit (0 when balanced)",
                    "example": 0,
                    "type": "integer"
                  },
                  "draftCount": {
                    "description": "Draft entries",
                    "example": 2,
                    "type": "integer"
                  },
                  "entryCount": {
                    "description": "Total posted journal entries",
                    "example": 897,
                    "type": "integer"
                  },
                  "isBalanced": {
                    "description": "貸借一致 — total debit equals total credit",
                    "example": true,
                    "type": "boolean"
                  },
                  "postedCount": {
                    "description": "Posted entries",
                    "example": 897,
                    "type": "integer"
                  },
                  "reversedCount": {
                    "description": "Reversed entries",
                    "example": 13,
                    "type": "integer"
                  },
                  "totalCredit": {
                    "description": "Sum of all credit amounts (JPY integer)",
                    "example": 12345678,
                    "type": "integer"
                  },
                  "totalDebit": {
                    "description": "Sum of all debit amounts (JPY integer)",
                    "example": 12345678,
                    "type": "integer"
                  }
                },
                "type": "object"
              },
              "pendingDraftsCount": {
                "description": "Journal entries in draft status",
                "example": 2,
                "type": "integer"
              },
              "sources": {
                "description": "Source data statistics for dock status indicators",
                "properties": {
                  "bank": {
                    "properties": {
                      "journalizedCount": {
                        "description": "Transactions with linked journal entries",
                        "example": 44,
                        "type": "integer"
                      },
                      "transactionCount": {
                        "description": "Total bank statement records",
                        "example": 1345,
                        "type": "integer"
                      }
                    },
                    "type": "object"
                  },
                  "expense": {
                    "properties": {
                      "documentCount": {
                        "description": "Total expense claim documents",
                        "example": 6,
                        "type": "integer"
                      },
                      "journalizedCount": {
                        "description": "Documents with linked journal entries",
                        "example": 0,
                        "type": "integer"
                      }
                    },
                    "type": "object"
                  },
                  "manual": {
                    "properties": {
                      "entryCount": {
                        "description": "Manual journal entries",
                        "example": 848,
                        "type": "integer"
                      }
                    },
                    "type": "object"
                  }
                },
                "type": "object"
              },
              "trialBalance": {
                "description": "Trial balance summary",
                "properties": {
                  "accountCount": {
                    "description": "Accounts with non-zero activity",
                    "example": 12,
                    "type": "integer"
                  },
                  "discrepancy": {
                    "example": 0,
                    "type": "integer"
                  },
                  "isBalanced": {
                    "example": true,
                    "type": "boolean"
                  },
                  "totalCredit": {
                    "example": 12345678,
                    "type": "integer"
                  },
                  "totalDebit": {
                    "example": 12345678,
                    "type": "integer"
                  },
                  "transactionCount": {
                    "description": "Posted journal entry lines (same basis as GL)",
                    "example": 48,
                    "type": "integer"
                  }
                },
                "type": "object"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Dock summary retrieved successfully",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "type": "object"
      },
      "Document": {
        "properties": {
          "client": {
            "description": "Linked trading partner details (included when available)",
            "nullable": true,
            "properties": {
              "address": {
                "example": "東京都渋谷区1-2-3",
                "nullable": true,
                "type": "string"
              },
              "client_type": {
                "description": "0=Customer, 1=Supplier, 2=Both",
                "example": 0,
                "type": "number"
              },
              "contact_person": {
                "example": "田中太郎",
                "type": "string"
              },
              "corporate_number": {
                "example": "1234567890123",
                "nullable": true,
                "type": "string"
              },
              "email": {
                "example": "contact@example.co.jp",
                "nullable": true,
                "type": "string"
              },
              "furigana": {
                "example": "カブシキガイシャサンプル",
                "nullable": true,
                "type": "string"
              },
              "id": {
                "format": "uuid",
                "type": "string"
              },
              "name": {
                "example": "株式会社サンプル",
                "type": "string"
              },
              "phone": {
                "example": "03-0000-0000",
                "nullable": true,
                "type": "string"
              },
              "registration_number": {
                "example": "T1234567890123",
                "nullable": true,
                "type": "string"
              }
            },
            "type": "object"
          },
          "client_id": {
            "description": "Linked trading partner (client) ID",
            "example": "550e8400-e29b-41d4-a716-446655440000",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "content": {
            "additionalProperties": true,
            "description": "Document content (structured JSON)",
            "example": {
              "items": [
                {
                  "name": "Service",
                  "price": 1000,
                  "quantity": 1
                }
              ],
              "title": "Sales Invoice",
              "total": 1000
            },
            "nullable": true,
            "type": "object"
          },
          "created_at": {
            "description": "Creation timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "deleted_at": {
            "description": "Timestamp when the document was deleted (null if not deleted)",
            "example": "2026-01-08T10:30:00Z",
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "deleted_by": {
            "description": "User ID who deleted the document (null if not deleted)",
            "example": "789e0123-e45b-67c8-d901-234567890123",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "document_name": {
            "description": "Document name",
            "example": "Sales Invoice - Client ABC",
            "maxLength": 50,
            "type": "string"
          },
          "document_type": {
            "description": "Document type classification",
            "enum": [
              "sales_quotation",
              "purchase_order",
              "delivery_note",
              "sales_invoice",
              "service_agreement",
              "travel",
              "claims",
              "fixed_asset",
              "payment",
              "salary_slip",
              "tax_journal",
              "tax_general_ledger",
              "tax_trial_balance",
              "tax_financial_statements",
              "tax_balance_sheet",
              "tax_profit_loss_statement",
              "tax_cash_flow_statement",
              "tax_shareholders_equity",
              "tax_notes_financial_statements",
              "tax_corporate",
              "tax_local",
              "tax_account_breakdown",
              "tax_application_details",
              "tax_business_overview",
              "company_info",
              "company_decision",
              "company_representative",
              "company_capital",
              "company_office_location",
              "rules_claims"
            ],
            "example": "sales_invoice",
            "type": "string"
          },
          "id": {
            "description": "Document unique identifier",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "is_deleted": {
            "description": "Whether document is soft-deleted (J-GAAP compliance)",
            "example": false,
            "type": "boolean"
          },
          "is_locked": {
            "description": "Whether document is locked for editing",
            "example": false,
            "type": "boolean"
          },
          "is_voided": {
            "description": "Whether document is voided (J-GAAP compliant cancellation)",
            "example": false,
            "type": "boolean"
          },
          "locked_at": {
            "description": "Timestamp when the document was locked (null if unlocked)",
            "example": "2026-01-07T10:30:00Z",
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "locked_by": {
            "description": "User ID who locked the document (null if unlocked)",
            "example": "789e0123-e45b-67c8-d901-234567890123",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "status": {
            "description": "Document publication status",
            "enum": [
              "draft",
              "published",
              "archived"
            ],
            "example": "published",
            "type": "string"
          },
          "updated_at": {
            "description": "Last update timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "user_id": {
            "description": "User identifier",
            "example": "789e0123-e45b-67c8-d901-234567890123",
            "format": "uuid",
            "type": "string"
          },
          "version": {
            "description": "Document version number",
            "example": 1,
            "minimum": 1,
            "type": "integer"
          },
          "void_reason": {
            "description": "Reason for voiding the document (required for J-GAAP compliance)",
            "example": "入力ミスのため無効化",
            "nullable": true,
            "type": "string"
          },
          "voided_at": {
            "description": "Timestamp when the document was voided (null if not voided)",
            "example": "2026-01-08T10:30:00Z",
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "voided_by": {
            "description": "User ID who voided the document (null if not voided)",
            "example": "789e0123-e45b-67c8-d901-234567890123",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          }
        },
        "required": [
          "id",
          "user_id",
          "document_name",
          "document_type",
          "status",
          "is_locked",
          "version",
          "created_at",
          "updated_at"
        ],
        "type": "object"
      },
      "DocumentActivityResponse": {
        "properties": {
          "data": {
            "properties": {
              "activities": {
                "items": {
                  "properties": {
                    "action": {
                      "enum": [
                        "created",
                        "updated",
                        "locked",
                        "unlocked",
                        "deleted",
                        "restored",
                        "voided",
                        "duplicated"
                      ],
                      "example": "locked",
                      "type": "string"
                    },
                    "changedAt": {
                      "format": "date-time",
                      "type": "string"
                    },
                    "changedBy": {
                      "properties": {
                        "avatar_url": {
                          "nullable": true,
                          "type": "string"
                        },
                        "id": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "username": {
                          "type": "string"
                        }
                      },
                      "type": "object"
                    },
                    "id": {
                      "format": "uuid",
                      "type": "string"
                    },
                    "metadata": {
                      "additionalProperties": true,
                      "type": "object"
                    },
                    "reason": {
                      "nullable": true,
                      "type": "string"
                    },
                    "version": {
                      "example": 3,
                      "type": "integer"
                    }
                  },
                  "type": "object"
                },
                "type": "array"
              },
              "pagination": {
                "properties": {
                  "hasMore": {
                    "type": "boolean"
                  },
                  "limit": {
                    "type": "integer"
                  },
                  "offset": {
                    "type": "integer"
                  },
                  "total": {
                    "type": "integer"
                  }
                },
                "type": "object"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Document activities retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "type": "object"
      },
      "DocumentAttachment": {
        "properties": {
          "created_at": {
            "description": "Upload timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "document_id": {
            "description": "Associated document identifier",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "file_name": {
            "description": "Original file name",
            "example": "receipt.pdf",
            "type": "string"
          },
          "file_size": {
            "description": "File size in bytes",
            "example": 1024000,
            "type": "integer"
          },
          "file_url": {
            "description": "File download URL",
            "example": "https://storage.example.com/files/receipt.pdf",
            "format": "uri",
            "type": "string"
          },
          "id": {
            "description": "Attachment unique identifier",
            "example": "456e7890-f12a-34b5-c678-901234567890",
            "format": "uuid",
            "type": "string"
          },
          "mime_type": {
            "description": "File MIME type",
            "example": "application/pdf",
            "type": "string"
          }
        },
        "required": [
          "id",
          "document_id",
          "file_name",
          "file_url",
          "created_at"
        ],
        "type": "object"
      },
      "DocumentAttachmentsResponse": {
        "properties": {
          "data": {
            "items": {
              "$ref": "#/components/schemas/DocumentAttachment"
            },
            "type": "array"
          },
          "message": {
            "example": "Document attachments retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "DocumentAuditLog": {
        "allOf": [
          {
            "$ref": "#/components/schemas/AuditLogEntry"
          },
          {
            "properties": {
              "document_id": {
                "description": "Referenced document ID",
                "format": "uuid",
                "type": "string"
              },
              "ip_address": {
                "description": "Client IP address at time of change (inet type)",
                "nullable": true,
                "type": "string"
              },
              "user_agent": {
                "description": "Client user agent string at time of change",
                "nullable": true,
                "type": "string"
              }
            },
            "required": [
              "document_id"
            ],
            "type": "object"
          }
        ],
        "description": "Audit log for documents table. Triggers: INSERT, UPDATE, DELETE (v5.13). Includes ip_address and user_agent columns not present in other audit tables."
      },
      "DocumentBatchResponse": {
        "properties": {
          "data": {
            "additionalProperties": {
              "properties": {
                "items": {
                  "items": {
                    "$ref": "#/components/schemas/Document"
                  },
                  "type": "array"
                },
                "pagination": {
                  "$ref": "#/components/schemas/Pagination"
                }
              },
              "required": [
                "items",
                "pagination"
              ],
              "type": "object"
            },
            "description": "Documents grouped by type (key = document_type)",
            "example": {
              "sales_invoice": {
                "items": [
                  {
                    "document_name": "Invoice 1",
                    "id": "123"
                  }
                ],
                "pagination": {
                  "currentPage": 1,
                  "hasNext": false,
                  "hasPrevious": false,
                  "pageSize": 100,
                  "totalItems": 45,
                  "totalPages": 1
                }
              },
              "sales_quotation": {
                "items": [
                  {
                    "document_name": "Quote 1",
                    "id": "456"
                  }
                ],
                "pagination": {
                  "currentPage": 1,
                  "hasNext": false,
                  "hasPrevious": false,
                  "pageSize": 100,
                  "totalItems": 30,
                  "totalPages": 1
                }
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Documents batch retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "DocumentCreateResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/Document"
          },
          "message": {
            "example": "Draft document created successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 201,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "DocumentGenerateResponse": {
        "properties": {
          "data": {
            "additionalProperties": true,
            "description": "Generated document content (JSON)",
            "type": "object"
          },
          "message": {
            "example": "Document content generated successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "DocumentGenerationStatus": {
        "description": "Document generation status",
        "enum": [
          "not_started",
          "generating",
          "draft",
          "final",
          "error"
        ],
        "example": "draft",
        "type": "string"
      },
      "DocumentHistory": {
        "description": "A version_control entry representing a document lifecycle event",
        "properties": {
          "change_type": {
            "description": "Type of lifecycle event",
            "enum": [
              "confirmed",
              "locked",
              "unlocked",
              "deleted",
              "restored",
              "voided",
              "duplicated"
            ],
            "example": "confirmed",
            "type": "string"
          },
          "changed_at": {
            "description": "When the action was performed",
            "format": "date-time",
            "type": "string"
          },
          "changed_by": {
            "description": "User ID who performed the action",
            "format": "uuid",
            "type": "string"
          },
          "created_at": {
            "description": "Record creation timestamp",
            "format": "date-time",
            "type": "string"
          },
          "entity_id": {
            "description": "Document ID (entity_id in version_control table)",
            "format": "uuid",
            "type": "string"
          },
          "entity_type": {
            "description": "Always \"documents\" for document history",
            "example": "documents",
            "type": "string"
          },
          "id": {
            "description": "Version control entry identifier",
            "format": "uuid",
            "type": "string"
          },
          "metadata": {
            "additionalProperties": true,
            "description": "Additional context (document_name, document_type, etc.)",
            "example": {
              "document_name": "経費精算書",
              "document_type": "claims",
              "new_status": "published",
              "previous_status": "draft"
            },
            "type": "object"
          },
          "reason": {
            "description": "Reason for the change (e.g., void reason)",
            "nullable": true,
            "type": "string"
          },
          "version": {
            "description": "Sequential version number (no gaps, starts at 1)",
            "example": 3,
            "type": "integer"
          }
        },
        "required": [
          "id",
          "entity_id",
          "version",
          "change_type",
          "changed_by",
          "changed_at"
        ],
        "type": "object"
      },
      "DocumentHistoryResponse": {
        "properties": {
          "data": {
            "properties": {
              "pagination": {
                "$ref": "#/components/schemas/Pagination"
              },
              "versions": {
                "items": {
                  "$ref": "#/components/schemas/DocumentHistory"
                },
                "type": "array"
              }
            },
            "required": [
              "versions",
              "pagination"
            ],
            "type": "object"
          },
          "message": {
            "example": "Document history retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "DocumentLinkResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/DocumentLinkResult"
          },
          "message": {
            "example": "Documents linked successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "DocumentLinkResult": {
        "properties": {
          "expensesSynced": {
            "description": "Number of expenses synchronized between documents",
            "example": 8,
            "type": "integer"
          },
          "relationship": {
            "properties": {
              "id": {
                "example": "rel12345-6789-abcd-efgh-ijklmnopqrst",
                "format": "uuid",
                "type": "string"
              },
              "sourceDocumentId": {
                "example": "123e4567-e89b-12d3-a456-426614174000",
                "format": "uuid",
                "type": "string"
              },
              "targetDocumentId": {
                "example": "456e7890-f12a-34b5-c678-901234567890",
                "format": "uuid",
                "type": "string"
              },
              "workflowType": {
                "example": "travel_to_claims",
                "type": "string"
              }
            },
            "type": "object"
          }
        },
        "required": [
          "relationship",
          "expensesSynced"
        ],
        "type": "object"
      },
      "DocumentLinkedDocumentsResponse": {
        "properties": {
          "documentId": {
            "format": "uuid",
            "type": "string"
          },
          "documentName": {
            "type": "string"
          },
          "documentType": {
            "type": "string"
          },
          "linkedDocumentCount": {
            "type": "integer"
          },
          "linkedDocuments": {
            "items": {
              "$ref": "#/components/schemas/GenericLinkedDocument"
            },
            "type": "array"
          },
          "linkedInvoices": {
            "items": {
              "$ref": "#/components/schemas/GenericLinkedDocument"
            },
            "type": "array"
          },
          "linkedReceipts": {
            "items": {
              "$ref": "#/components/schemas/GenericLinkedDocument"
            },
            "type": "array"
          },
          "totalAllocatedAmount": {
            "type": "number"
          }
        },
        "type": "object"
      },
      "DocumentListItem": {
        "description": "Document list item with computed fields (totalAmount, linkedDocumentCount, linkStats when requested)",
        "properties": {
          "createdAt": {
            "description": "Creation timestamp",
            "example": "2025-11-28T07:01:56.663Z",
            "format": "date-time",
            "type": "string"
          },
          "deletedAt": {
            "description": "Timestamp when document was deleted",
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "displayTitle": {
            "description": "Descriptive title derived from content at read time (Sep 2026).\nThe stored documentName is never changed; the document type is not repeated.\n- claims: the place most lines name · the top two 勘定科目 by amount + line count\n- travel: the destination without its address\n- salary_slip: payee · purpose · period\n- payment: payee · type · date, or 合算精算 · 申請書N件 · date\n\nNull when the content has nothing to derive from (show documentName).",
            "example": "高原拠点 · 消耗品費/会議費 21件",
            "nullable": true,
            "type": "string"
          },
          "documentName": {
            "description": "Document name",
            "example": "20250728-29_tsumagoi_ranch_trip",
            "type": "string"
          },
          "documentType": {
            "description": "Document type classification",
            "enum": [
              "sales_quotation",
              "purchase_order",
              "delivery_note",
              "sales_invoice",
              "service_agreement",
              "travel",
              "claims",
              "fixed_asset",
              "payment",
              "salary_slip",
              "company_info"
            ],
            "example": "claims",
            "type": "string"
          },
          "id": {
            "description": "Document unique identifier",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "isDeleted": {
            "description": "Whether document is soft-deleted",
            "example": false,
            "nullable": true,
            "type": "boolean"
          },
          "isLocked": {
            "description": "Whether document is locked for editing",
            "example": true,
            "nullable": true,
            "type": "boolean"
          },
          "isVoided": {
            "description": "Whether document is voided",
            "example": false,
            "nullable": true,
            "type": "boolean"
          },
          "linkedDocumentCount": {
            "description": "Count of linked documents (v4.30).\nIncludes links from both:\n- document_relationships table (generic document links)\n- expense_claim_receipts table (expense claim specific links)\n\nReturns 0 if no links exist",
            "example": 3,
            "minimum": 0,
            "type": "integer"
          },
          "linkedInvoiceCount": {
            "description": "Number of invoices linked to this document (v5.3).\n\nOnly present when include_link_stats=true query parameter is set.\nCounts related documents from document_relationships table\nwhere related document type is sales_invoice or purchase_order.",
            "example": 1,
            "minimum": 0,
            "nullable": true,
            "type": "integer"
          },
          "linkedReceiptCount": {
            "description": "Number of receipts linked to this document (v5.3).\n\nOnly present when include_link_stats=true query parameter is set.\nSpecifically counts records in expense_claim_receipts table.\nUseful for expense wizard to show utilization of claims documents.",
            "example": 2,
            "minimum": 0,
            "nullable": true,
            "type": "integer"
          },
          "linkedReceiptTotal": {
            "description": "Sum of amounts from linked receipts (v5.3).\n\nOnly present when include_link_stats=true query parameter is set.\nAggregates totalAmount from all linked receipt documents.\nUsed to calculate remaining/available amount for new receipt linking.",
            "example": 8500,
            "nullable": true,
            "type": "number"
          },
          "lockedAt": {
            "description": "Timestamp when document was locked",
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "paymentType": {
            "description": "Payment type for salary_slip and payment documents (v4.43).\n\nFor salary_slip: Retrieved from pay_slips.payment_type\nFor payment: Auto-detected from document name keywords\n\nValues:\n- salary: 給与 (regular monthly salary)\n- bonus: 賞与 (seasonal bonus)\n- executive: 役員報酬 (executive compensation)\n- fee: 報酬 (professional fees)\n- reimbursement: 経費精算 (expense reimbursement)\n- per_diem: 日当 (daily allowance)\n\nReturns null for other document types or if not detected.",
            "enum": [
              "salary",
              "bonus",
              "executive",
              "fee",
              "reimbursement",
              "per_diem"
            ],
            "example": "bonus",
            "nullable": true,
            "type": "string"
          },
          "paymentTypeLabel": {
            "description": "Japanese label for payment type (v4.43).\n\nUsed for display in frontend UI badges.\n\nReturns null if paymentType is null.",
            "enum": [
              "給与",
              "賞与",
              "役員報酬",
              "報酬",
              "経費精算",
              "日当"
            ],
            "example": "賞与",
            "nullable": true,
            "type": "string"
          },
          "status": {
            "description": "Document publication status",
            "enum": [
              "draft",
              "published"
            ],
            "example": "published",
            "type": "string"
          },
          "totalAmount": {
            "description": "Computed total amount from document content (v4.30).\nExtracted from JSONB based on documentType:\n- claims: content.summary.reimbursementAmount OR content.summary.totalAmount\n- payment: content.paymentInfo.amount  \n- salary_slip: content.totals.netPay\n- sales_invoice/quotation/etc: content.summary.totalAmount\n\nReturns null if amount not found (distinguishes \"not available\" from \"zero yen\")",
            "example": 188891,
            "nullable": true,
            "type": "number"
          },
          "updatedAt": {
            "description": "Last update timestamp",
            "example": "2025-11-28T07:03:19.163Z",
            "format": "date-time",
            "type": "string"
          },
          "voidReason": {
            "description": "Reason for voiding",
            "nullable": true,
            "type": "string"
          },
          "voidedAt": {
            "description": "Timestamp when document was voided",
            "format": "date-time",
            "nullable": true,
            "type": "string"
          }
        },
        "required": [
          "id",
          "documentName",
          "documentType",
          "status",
          "createdAt",
          "updatedAt",
          "linkedDocumentCount"
        ],
        "type": "object"
      },
      "DocumentListResponse": {
        "description": "Paginated document list with computed fields (totalAmount, linkedDocumentCount)",
        "example": {
          "data": {
            "items": [
              {
                "createdAt": "2025-11-28T07:01:56.663Z",
                "deletedAt": null,
                "documentName": "20250728-29_tsumagoi_ranch_trip",
                "documentType": "claims",
                "id": "123e4567-e89b-12d3-a456-426614174000",
                "isDeleted": false,
                "isLocked": true,
                "isVoided": false,
                "linkedDocumentCount": 3,
                "lockedAt": "2025-11-28T07:03:19.163Z",
                "status": "published",
                "totalAmount": 188891,
                "updatedAt": "2025-11-28T07:03:19.163Z",
                "voidReason": null,
                "voidedAt": null
              },
              {
                "createdAt": "2025-12-01T09:00:00.000Z",
                "deletedAt": null,
                "documentName": "202501_salary_tanaka",
                "documentType": "salary_slip",
                "id": "456e7890-e89b-12d3-a456-426614174001",
                "isDeleted": false,
                "isLocked": false,
                "isVoided": false,
                "linkedDocumentCount": 0,
                "lockedAt": null,
                "paymentType": "salary",
                "paymentTypeLabel": "給与",
                "status": "draft",
                "totalAmount": 350000,
                "updatedAt": "2025-12-01T09:30:00.000Z",
                "voidReason": null,
                "voidedAt": null
              },
              {
                "createdAt": "2025-12-25T10:00:00.000Z",
                "deletedAt": null,
                "documentName": "20251225_支払明細書_JPY250000",
                "documentType": "payment",
                "id": "789e0123-e89b-12d3-a456-426614174002",
                "isDeleted": false,
                "isLocked": false,
                "isVoided": false,
                "linkedDocumentCount": 1,
                "lockedAt": null,
                "paymentType": null,
                "paymentTypeLabel": null,
                "status": "published",
                "totalAmount": 250000,
                "updatedAt": "2025-12-25T10:30:00.000Z",
                "voidReason": null,
                "voidedAt": null
              }
            ],
            "pagination": {
              "currentPage": 1,
              "hasNext": true,
              "hasPrevious": false,
              "pageSize": 20,
              "totalItems": 42,
              "totalPages": 3
            }
          },
          "message": "Documents retrieved successfully",
          "statusCode": 200
        },
        "properties": {
          "data": {
            "properties": {
              "items": {
                "description": "Document items with computed fields",
                "items": {
                  "$ref": "#/components/schemas/DocumentListItem"
                },
                "type": "array"
              },
              "pagination": {
                "properties": {
                  "currentPage": {
                    "example": 1,
                    "type": "number"
                  },
                  "hasNext": {
                    "example": true,
                    "type": "boolean"
                  },
                  "hasPrevious": {
                    "example": false,
                    "type": "boolean"
                  },
                  "pageSize": {
                    "example": 20,
                    "type": "number"
                  },
                  "totalItems": {
                    "example": 150,
                    "type": "number"
                  },
                  "totalPages": {
                    "example": 8,
                    "type": "number"
                  }
                },
                "required": [
                  "currentPage",
                  "pageSize",
                  "totalItems",
                  "totalPages",
                  "hasNext",
                  "hasPrevious"
                ],
                "type": "object"
              }
            },
            "required": [
              "items",
              "pagination"
            ],
            "type": "object"
          },
          "message": {
            "example": "Document retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "DocumentMatch": {
        "properties": {
          "amount": {
            "description": "Document amount",
            "example": 15000,
            "format": "decimal",
            "type": "number"
          },
          "documentId": {
            "description": "Document identifier",
            "example": "doc_456789",
            "type": "string"
          },
          "documentTitle": {
            "description": "Document title or description",
            "example": "出張費精算書 - 東京出張",
            "type": "string"
          },
          "documentType": {
            "$ref": "#/components/schemas/DocumentType"
          },
          "matchReasons": {
            "description": "Reasons for the match",
            "example": [
              "金額が完全一致",
              "日付が近い",
              "申請者が同じ"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "matchScore": {
            "description": "Match confidence score",
            "example": 0.95,
            "format": "double",
            "maximum": 1,
            "minimum": 0,
            "type": "number"
          },
          "suggestedAction": {
            "$ref": "#/components/schemas/SuggestedAction"
          }
        },
        "required": [
          "documentId",
          "documentType",
          "documentTitle",
          "amount",
          "matchScore",
          "matchReasons",
          "suggestedAction"
        ],
        "type": "object"
      },
      "DocumentRelationship": {
        "description": "Represents a relationship between two documents in Japanese B2B workflow",
        "properties": {
          "childDocument": {
            "description": "Summary of the child document",
            "properties": {
              "documentName": {
                "example": "請求書_ABC株式会社_2026-01",
                "type": "string"
              },
              "documentType": {
                "example": "sales_invoice",
                "type": "string"
              },
              "id": {
                "format": "uuid",
                "type": "string"
              },
              "status": {
                "example": "draft",
                "type": "string"
              }
            },
            "type": "object"
          },
          "childDocumentId": {
            "description": "ID of the child document (e.g., 請求書)",
            "example": "789e0123-e89b-12d3-a456-426614174002",
            "format": "uuid",
            "type": "string"
          },
          "createdAt": {
            "description": "When the relationship was created",
            "example": "2026-01-10T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "createdBy": {
            "description": "User who created the relationship",
            "format": "uuid",
            "type": "string"
          },
          "id": {
            "description": "Unique identifier for the relationship",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "parentDocument": {
            "description": "Summary of the parent document",
            "properties": {
              "documentName": {
                "example": "見積書_ABC株式会社_2026-01",
                "type": "string"
              },
              "documentType": {
                "example": "sales_quotation",
                "type": "string"
              },
              "id": {
                "format": "uuid",
                "type": "string"
              },
              "status": {
                "example": "published",
                "type": "string"
              }
            },
            "type": "object"
          },
          "parentDocumentId": {
            "description": "ID of the parent document (e.g., 見積書)",
            "example": "456e7890-e89b-12d3-a456-426614174001",
            "format": "uuid",
            "type": "string"
          },
          "relationshipMetadata": {
            "additionalProperties": true,
            "description": "Additional metadata about the relationship",
            "nullable": true,
            "type": "object"
          },
          "relationshipType": {
            "description": "Type of relationship between documents",
            "enum": [
              "quotation_to_order",
              "order_to_delivery",
              "delivery_to_invoice",
              "quotation_to_invoice",
              "buyer_attachment",
              "supporting_document",
              "revision_of",
              "supersedes",
              "references",
              "related_to"
            ],
            "example": "quotation_to_invoice",
            "type": "string"
          }
        },
        "required": [
          "id",
          "parentDocumentId",
          "childDocumentId",
          "relationshipType",
          "createdAt",
          "createdBy"
        ],
        "type": "object"
      },
      "DocumentRelationshipsResponse": {
        "properties": {
          "data": {
            "properties": {
              "pagination": {
                "properties": {
                  "hasMore": {
                    "example": false,
                    "type": "boolean"
                  },
                  "limit": {
                    "example": 50,
                    "type": "integer"
                  },
                  "offset": {
                    "example": 0,
                    "type": "integer"
                  },
                  "total": {
                    "example": 5,
                    "type": "integer"
                  }
                },
                "type": "object"
              },
              "relationships": {
                "items": {
                  "$ref": "#/components/schemas/DocumentRelationship"
                },
                "type": "array"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Document relationships retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "type": "object"
      },
      "DocumentResponse": {
        "description": "Response structure for GET /documents/:id - contains document with linked client",
        "properties": {
          "data": {
            "properties": {
              "document": {
                "allOf": [
                  {
                    "$ref": "#/components/schemas/Document"
                  },
                  {
                    "description": "Document with linked client information",
                    "properties": {
                      "client": {
                        "description": "Linked trading partner details (populated when client_id exists)",
                        "nullable": true,
                        "properties": {
                          "address": {
                            "example": "東京都渋谷区1-2-3",
                            "nullable": true,
                            "type": "string"
                          },
                          "client_type": {
                            "description": "0=Customer, 1=Supplier, 2=Both",
                            "example": 0,
                            "type": "number"
                          },
                          "contact_person": {
                            "example": "田中太郎",
                            "type": "string"
                          },
                          "corporate_number": {
                            "example": "1234567890123",
                            "nullable": true,
                            "type": "string"
                          },
                          "email": {
                            "example": "contact@example.co.jp",
                            "nullable": true,
                            "type": "string"
                          },
                          "furigana": {
                            "example": "カブシキガイシャサンプル",
                            "nullable": true,
                            "type": "string"
                          },
                          "id": {
                            "format": "uuid",
                            "type": "string"
                          },
                          "name": {
                            "example": "株式会社サンプル",
                            "type": "string"
                          },
                          "phone": {
                            "example": "03-0000-0000",
                            "nullable": true,
                            "type": "string"
                          },
                          "registration_number": {
                            "example": "T1234567890123",
                            "nullable": true,
                            "type": "string"
                          }
                        },
                        "type": "object"
                      },
                      "client_id": {
                        "description": "Linked trading partner ID",
                        "example": "550e8400-e29b-41d4-a716-446655440000",
                        "format": "uuid",
                        "nullable": true,
                        "type": "string"
                      }
                    },
                    "type": "object"
                  }
                ]
              },
              "documentVersions": {
                "description": "Version history metadata",
                "properties": {
                  "change_type": {
                    "type": "string"
                  },
                  "changed_at": {
                    "format": "date-time",
                    "type": "string"
                  },
                  "changed_by": {
                    "type": "string"
                  },
                  "id": {
                    "type": "string"
                  },
                  "reason": {
                    "type": "string"
                  },
                  "version": {
                    "type": "number"
                  }
                },
                "type": "object"
              }
            },
            "required": [
              "document",
              "documentVersions"
            ],
            "type": "object"
          },
          "message": {
            "example": "Document retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "DocumentSearchResponse": {
        "properties": {
          "documents": {
            "items": {
              "properties": {
                "amount": {
                  "type": "number"
                },
                "date": {
                  "type": "string"
                },
                "documentName": {
                  "type": "string"
                },
                "documentType": {
                  "type": "string"
                },
                "id": {
                  "format": "uuid",
                  "type": "string"
                },
                "matchReason": {
                  "description": "Japanese description of match reasons",
                  "type": "string"
                },
                "matchScore": {
                  "description": "Match score 0-100",
                  "maximum": 100,
                  "minimum": 0,
                  "type": "number"
                },
                "status": {
                  "type": "string"
                },
                "suggestedLinkageType": {
                  "$ref": "#/components/schemas/LinkageType"
                },
                "vendorName": {
                  "type": "string"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "query": {
            "properties": {
              "amount": {
                "type": "number"
              },
              "amountRange": {
                "items": {
                  "type": "number"
                },
                "maxItems": 2,
                "minItems": 2,
                "type": "array"
              },
              "date": {
                "type": "string"
              },
              "dateRange": {
                "items": {
                  "type": "string"
                },
                "maxItems": 2,
                "minItems": 2,
                "type": "array"
              }
            },
            "type": "object"
          },
          "totalCount": {
            "description": "Total matching documents",
            "type": "integer"
          }
        },
        "type": "object"
      },
      "DocumentSearchResult": {
        "properties": {
          "amount": {
            "description": "Transaction amount",
            "example": 125000,
            "format": "decimal",
            "type": "number"
          },
          "createdAt": {
            "example": "2024-03-15T10:00:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "description": {
            "description": "Transaction description",
            "nullable": true,
            "type": "string"
          },
          "documentType": {
            "description": "Document type",
            "example": "receipt",
            "type": "string"
          },
          "id": {
            "description": "Document ID",
            "format": "uuid",
            "type": "string"
          },
          "integrityMode": {
            "description": "How integrity is evidenced: none, server_hash (SHA-256 by this server) or certified_tsa",
            "enum": [
              "none",
              "server_hash",
              "certified_tsa"
            ],
            "example": "server_hash",
            "type": "string"
          },
          "isIntegrityHashed": {
            "description": "Whether the document carries a server-side integrity hash (not a 認定タイムスタンプ)",
            "example": true,
            "type": "boolean"
          },
          "isTimestamped": {
            "deprecated": true,
            "description": "Deprecated alias of isIntegrityHashed — kept for API compatibility. True means a server-side integrity hash (SHA-256), NOT a 認定タイムスタンプ: no accredited TSA is integrated.",
            "example": true,
            "type": "boolean"
          },
          "source": {
            "description": "Where the document row comes from",
            "enum": [
              "expense",
              "file_upload"
            ],
            "example": "file_upload",
            "type": "string"
          },
          "transactionDate": {
            "description": "Transaction date in YYYYMMDD format",
            "example": 20240315,
            "type": "integer"
          },
          "vendorName": {
            "description": "Vendor name",
            "example": "株式会社サンプル",
            "type": "string"
          }
        },
        "required": [
          "id",
          "documentType",
          "transactionDate",
          "amount",
          "vendorName",
          "isTimestamped",
          "isIntegrityHashed",
          "integrityMode",
          "source",
          "createdAt"
        ],
        "type": "object"
      },
      "DocumentStatistics": {
        "properties": {
          "by_status": {
            "additionalProperties": {
              "type": "integer"
            },
            "description": "Document count by status",
            "example": {
              "archived": 10,
              "draft": 20,
              "published": 120
            },
            "type": "object"
          },
          "by_type": {
            "additionalProperties": {
              "type": "integer"
            },
            "description": "Document count by type",
            "example": {
              "sales_invoice": 45,
              "sales_quotation": 30,
              "service_agreement": 25
            },
            "type": "object"
          },
          "recent_activity": {
            "description": "Documents modified in last 30 days",
            "example": 25,
            "type": "integer"
          },
          "total_documents": {
            "description": "Total number of documents",
            "example": 150,
            "type": "integer"
          }
        },
        "required": [
          "total_documents",
          "by_type",
          "by_status",
          "recent_activity"
        ],
        "type": "object"
      },
      "DocumentStatisticsResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/DocumentStatistics"
          },
          "message": {
            "example": "Document statistics retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "DocumentStatus": {
        "properties": {
          "document_id": {
            "description": "Generated document ID",
            "example": "doc_123456",
            "type": "string"
          },
          "document_type": {
            "description": "Type of document",
            "example": "articles_of_incorporation",
            "type": "string"
          },
          "error_message": {
            "description": "Error message if generation failed",
            "example": "Template processing error",
            "type": "string"
          },
          "generated_at": {
            "description": "Document generation timestamp",
            "example": "2024-01-15T10:30:00Z",
            "format": "date-time",
            "type": "string"
          },
          "status": {
            "$ref": "#/components/schemas/DocumentGenerationStatus"
          }
        },
        "required": [
          "document_type",
          "status"
        ],
        "type": "object"
      },
      "DocumentStatusResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/DocumentStatus"
          },
          "success": {
            "example": true,
            "type": "boolean"
          },
          "timestamp": {
            "example": "2024-01-15T10:30:00Z",
            "format": "date-time",
            "type": "string"
          }
        },
        "required": [
          "success",
          "data",
          "timestamp"
        ],
        "type": "object"
      },
      "DocumentStructuredData": {
        "description": "Standardized structured data extracted from documents",
        "properties": {
          "amount": {
            "description": "合計金額 (税込)",
            "nullable": true,
            "type": "number"
          },
          "category": {
            "description": "カテゴリ/分類",
            "nullable": true,
            "type": "string"
          },
          "date": {
            "description": "日付 (ISO format YYYY-MM-DD)",
            "nullable": true,
            "type": "string"
          },
          "description": {
            "description": "摘要/件名",
            "nullable": true,
            "type": "string"
          },
          "invoice_number": {
            "description": "請求書番号/伝票番号",
            "nullable": true,
            "type": "string"
          },
          "items": {
            "items": {
              "properties": {
                "amount": {
                  "type": "number"
                },
                "description": {
                  "type": "string"
                },
                "quantity": {
                  "type": "number"
                },
                "unit_price": {
                  "type": "number"
                }
              },
              "type": "object"
            },
            "nullable": true,
            "type": "array"
          },
          "notes": {
            "nullable": true,
            "type": "string"
          },
          "payment_method": {
            "nullable": true,
            "type": "string"
          },
          "subtotal": {
            "description": "小計/税抜金額",
            "nullable": true,
            "type": "number"
          },
          "tax_amount": {
            "description": "消費税額",
            "nullable": true,
            "type": "number"
          },
          "vendor": {
            "description": "取引先/会社名",
            "nullable": true,
            "type": "string"
          }
        },
        "type": "object"
      },
      "DocumentTemplate": {
        "properties": {
          "created_at": {
            "format": "date-time",
            "type": "string"
          },
          "description": {
            "nullable": true,
            "type": "string"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "is_archived": {
            "type": "boolean"
          },
          "name": {
            "example": "業務委託完了報告書",
            "type": "string"
          },
          "template_json": {
            "description": "Field layout JSON (camelCase keys + customFields extension point)",
            "type": "object"
          },
          "updated_at": {
            "format": "date-time",
            "type": "string"
          }
        },
        "type": "object"
      },
      "DocumentType": {
        "description": "Linkable document types",
        "enum": [
          "receipt",
          "invoice",
          "claims",
          "payroll",
          "payment_statement",
          "credit_card",
          "tax",
          "quote",
          "purchase_order",
          "delivery_note",
          "fixed_asset",
          "loan",
          "other"
        ],
        "type": "string"
      },
      "DocumentViewerConfig": {
        "description": "Document viewer configuration and display preferences (v4.28 - Added document style variants)",
        "properties": {
          "color_scheme": {
            "description": "Color scheme (0: DEFAULT, 1: HIGH_CONTRAST, 2: SEPIA, 3: DARK)",
            "enum": [
              0,
              1,
              2,
              3
            ],
            "example": 0,
            "type": "integer"
          },
          "document_style_variant": {
            "description": "Visual styling preset for Japanese business documents (v4.28)\n\n| Value | Name | Japanese | Description |\n|-------|------|----------|-------------|\n| 0 | STANDARD | 標準 | Clean modern style with neutral colors |\n| 1 | TRADITIONAL | 伝統的 | Mincho font, classic borders, formal appearance |\n| 2 | MINIMAL | シンプル | Zen-inspired minimal design, maximum whitespace |\n| 3 | FORMAL | 公式 | Government/legal format with structured layout |\n| 4 | MODERN | モダン | Soft borders, modern typography, subtle shadows |",
            "enum": [
              0,
              1,
              2,
              3,
              4
            ],
            "example": 0,
            "type": "integer"
          },
          "font_family": {
            "description": "Font family (0: DEFAULT, 1: MINCHO, 2: GOTHIC, 3: MONO)",
            "enum": [
              0,
              1,
              2,
              3
            ],
            "example": 0,
            "type": "integer"
          },
          "font_size": {
            "description": "Font size (0: XS, 1: SM, 2: BASE, 3: LG, 4: XL)",
            "enum": [
              0,
              1,
              2,
              3,
              4
            ],
            "example": 2,
            "type": "integer"
          },
          "layout_density": {
            "description": "Layout density (0: COMPACT, 1: NORMAL, 2: SPACIOUS)",
            "enum": [
              0,
              1,
              2
            ],
            "example": 1,
            "type": "integer"
          },
          "max_width": {
            "description": "Maximum width (0: NARROW, 1: NORMAL, 2: WIDE, 3: FULL)",
            "enum": [
              0,
              1,
              2,
              3
            ],
            "example": 1,
            "type": "integer"
          },
          "print_color_scheme": {
            "description": "Print color scheme (0: DEFAULT, 1: PRINT_FRIENDLY)",
            "enum": [
              0,
              1
            ],
            "example": 1,
            "type": "integer"
          },
          "print_font_size": {
            "description": "Print font size (0: XS, 1: SM, 2: BASE, 3: LG, 4: XL)",
            "enum": [
              0,
              1,
              2,
              3,
              4
            ],
            "example": 1,
            "type": "integer"
          },
          "selected_preset_id": {
            "description": "ID of the currently selected visual preset (v4.28)\n\n**Built-in Preset IDs:**\n| ID | Name | Japanese | Theme |\n|----|------|----------|-------|\n| preset-wabi | Wabi | 侘び | Rustic tranquility |\n| preset-miyabi | Miyabi | 雅び | Courtly elegance |\n| preset-zen | Zen | 禅 | Meditative clarity |\n| preset-iki | Iki | 粋 | Urban sophistication |\n| preset-rin | Rin | 凛 | Dignified formality |\n\n**Custom Presets:** Follow format `custom-{timestamp}` (e.g., `custom-1704067200000`)\n\n**null:** No preset selected, using individual settings",
            "example": "preset-wabi",
            "nullable": true,
            "type": "string"
          },
          "show_borders": {
            "description": "Display borders around document elements",
            "example": true,
            "type": "boolean"
          },
          "show_line_numbers": {
            "description": "Display line numbers in document viewer",
            "example": false,
            "type": "boolean"
          },
          "show_shadows": {
            "description": "Display shadows for visual depth",
            "example": true,
            "type": "boolean"
          }
        },
        "type": "object"
      },
      "DocumentViewerConfigResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/DocumentViewerConfig",
            "description": "Document viewer configuration settings"
          },
          "message": {
            "example": "Document viewer configuration retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "DriftFinding": {
        "properties": {
          "accountCode": {
            "nullable": true,
            "type": "string"
          },
          "accountName": {
            "nullable": true,
            "type": "string"
          },
          "actorId": {
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "currentAmount": {
            "nullable": true,
            "type": "number"
          },
          "delta": {
            "description": "Signed 税引前利益 effect for entries; signed account movement for account_delta",
            "nullable": true,
            "type": "number"
          },
          "detectedAt": {
            "format": "date-time",
            "type": "string"
          },
          "entryDate": {
            "nullable": true,
            "type": "integer"
          },
          "entryNumber": {
            "nullable": true,
            "type": "string"
          },
          "explanation": {
            "nullable": true,
            "type": "string"
          },
          "filedAmount": {
            "nullable": true,
            "type": "number"
          },
          "filedReturnId": {
            "format": "uuid",
            "type": "string"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "journalEntryId": {
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "kind": {
            "enum": [
              "entry_created",
              "entry_reversed",
              "entry_restored",
              "entry_changed",
              "account_delta"
            ],
            "type": "string"
          },
          "occurredAt": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "reason": {
            "description": "Reason declared at edit time (x-filing-change-reason)",
            "nullable": true,
            "type": "string"
          },
          "resolvedAt": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "status": {
            "enum": [
              "pending",
              "amend_return",
              "fix_books",
              "explained"
            ],
            "type": "string"
          },
          "statusAt": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "statusLabel": {
            "description": "判断待ち / 修正申告が必要 / 帳簿側を修正 / 説明済み",
            "type": "string"
          }
        },
        "required": [
          "id",
          "filedReturnId",
          "kind",
          "status",
          "statusLabel",
          "detectedAt"
        ],
        "type": "object"
      },
      "DriftFindingResult": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/DriftFinding"
          },
          "success": {
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "DriftFindingsResult": {
        "properties": {
          "data": {
            "properties": {
              "findings": {
                "items": {
                  "$ref": "#/components/schemas/DriftFinding"
                },
                "type": "array"
              }
            },
            "required": [
              "findings"
            ],
            "type": "object"
          },
          "success": {
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "DriveInboxItem": {
        "additionalProperties": false,
        "properties": {
          "amount": {
            "nullable": true,
            "type": "number"
          },
          "amountJpy": {
            "nullable": true,
            "type": "number"
          },
          "appliedFolderId": {
            "nullable": true,
            "type": "string"
          },
          "appliedName": {
            "nullable": true,
            "type": "string"
          },
          "appliedWithoutDrive": {
            "description": "Finished with 「Driveを変えずに完了」: the file was gone or moved, Drive was not changed",
            "type": "boolean"
          },
          "attempts": {
            "description": "Analyses tried; a transient failure is retried until the third",
            "type": "integer"
          },
          "bankStatementId": {
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "category": {
            "description": "ExpenseCategory (the wizard’s category)",
            "nullable": true,
            "type": "integer"
          },
          "createdAt": {
            "format": "date-time",
            "type": "string"
          },
          "currency": {
            "nullable": true,
            "type": "string"
          },
          "decidedAt": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "documentId": {
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "driveFileId": {
            "type": "string"
          },
          "error": {
            "nullable": true,
            "type": "string"
          },
          "evidenceLinked": {
            "description": "SBC made the 証憑 link (reject and undo remove only such a link)",
            "type": "boolean"
          },
          "expenseId": {
            "description": "A 立替 expense already booked",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "extractedDate": {
            "format": "date",
            "nullable": true,
            "type": "string"
          },
          "fileUploadId": {
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "flags": {
            "description": "Why a proposal needs a look: no_date, invalid_date, no_amount, foreign_currency, fx_rate_missing, fx_rate_approximate, fx_approximate_match, foreign_needs_choice, amount_needs_review, multiple_bank_candidates, bank_row_has_evidence, already_attached, already_booked_expense, no_archive_root, no_fiscal_year_folder, extraction_empty, duplicate_in_inbox, left_inbox, undone, unsupported_type, too_large. Approve without an explicit bankStatementId is only for a clean card match (kind card and none of no_date, invalid_date, fx_approximate_match, fx_rate_approximate, bank_row_has_evidence, amount_needs_review, multiple_bank_candidates, foreign_needs_choice).",
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "kind": {
            "description": "card = paid from the company account (a bank row matched); claim = 立替 candidate; null = the owner must choose (a foreign receipt with no bank match)",
            "enum": [
              "card",
              "claim"
            ],
            "nullable": true,
            "type": "string"
          },
          "matchConfidence": {
            "maximum": 1,
            "minimum": 0,
            "nullable": true,
            "type": "number"
          },
          "mimeType": {
            "type": "string"
          },
          "modifiedTime": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "name": {
            "description": "The name in Drive when SBC found it",
            "type": "string"
          },
          "originalName": {
            "description": "Undo record: the name in Drive before SBC renamed it",
            "nullable": true,
            "type": "string"
          },
          "originalParentIds": {
            "description": "Undo record: the folders the file was in before SBC moved it",
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "proposedFolderPath": {
            "description": "Relative to the archive root",
            "example": "FY2026_20260216-20270215/30_card_GMO/20261001-31_GMO",
            "nullable": true,
            "type": "string"
          },
          "proposedName": {
            "example": "20261003_消耗品費_コメリ_3280円.pdf",
            "nullable": true,
            "type": "string"
          },
          "sizeBytes": {
            "nullable": true,
            "type": "integer"
          },
          "status": {
            "enum": [
              "new",
              "analyzed",
              "approved",
              "applied",
              "rejected",
              "failed"
            ],
            "type": "string"
          },
          "undoneAt": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "vendor": {
            "nullable": true,
            "type": "string"
          },
          "webViewLink": {
            "nullable": true,
            "type": "string"
          }
        },
        "required": [
          "id",
          "driveFileId",
          "name",
          "mimeType",
          "sizeBytes",
          "modifiedTime",
          "webViewLink",
          "status",
          "attempts",
          "extractedDate",
          "amount",
          "currency",
          "amountJpy",
          "vendor",
          "category",
          "kind",
          "proposedName",
          "proposedFolderPath",
          "bankStatementId",
          "expenseId",
          "documentId",
          "matchConfidence",
          "flags",
          "fileUploadId",
          "originalName",
          "originalParentIds",
          "appliedName",
          "appliedFolderId",
          "appliedWithoutDrive",
          "evidenceLinked",
          "decidedAt",
          "undoneAt",
          "error",
          "createdAt"
        ],
        "type": "object"
      },
      "DuplicateDocumentRequest": {
        "properties": {
          "content": {
            "additionalProperties": true,
            "description": "Override content for the duplicated document (optional)",
            "type": "object"
          },
          "document_name": {
            "description": "Name for the duplicated document (optional, defaults to \"Copy of {original}\")",
            "example": "Sales Invoice Copy",
            "maxLength": 50,
            "type": "string"
          }
        },
        "type": "object"
      },
      "DuplicateDocumentResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/Document"
          },
          "message": {
            "example": "Document duplicated successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 201,
            "type": "number"
          }
        },
        "type": "object"
      },
      "EBookDocumentMetadata": {
        "properties": {
          "amount": {
            "description": "Transaction amount in JPY",
            "example": 125000,
            "format": "decimal",
            "type": "number"
          },
          "createdAt": {
            "example": "2024-03-15T10:00:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "currencyCode": {
            "default": "JPY",
            "description": "Currency code (ISO 4217)",
            "example": "JPY",
            "type": "string"
          },
          "description": {
            "description": "Transaction description",
            "example": "Office supplies purchase",
            "nullable": true,
            "type": "string"
          },
          "documentType": {
            "$ref": "#/components/schemas/EBookDocumentType"
          },
          "fileHash": {
            "description": "SHA-256 hash for file integrity verification",
            "example": "a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3",
            "type": "string"
          },
          "id": {
            "description": "Document unique identifier",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "originalFileName": {
            "description": "Original file name",
            "example": "receipt_20240315.pdf",
            "type": "string"
          },
          "storageUrl": {
            "description": "File storage URL",
            "example": "https://storage.example.com/documents/receipt_20240315.pdf",
            "type": "string"
          },
          "timestampToken": {
            "description": "Timestamp token from trusted authority",
            "example": "ts_a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3",
            "nullable": true,
            "type": "string"
          },
          "timestampedAt": {
            "description": "Timestamp application date",
            "example": "2024-03-15T10:30:00.000Z",
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "transactionDate": {
            "description": "Transaction date in YYYYMMDD format",
            "example": 20240315,
            "type": "integer"
          },
          "updatedAt": {
            "example": "2024-03-15T10:00:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "userId": {
            "description": "User who registered the document",
            "format": "uuid",
            "type": "string"
          },
          "vendorName": {
            "description": "Vendor/payee name for legal search requirements",
            "example": "株式会社サンプル",
            "type": "string"
          }
        },
        "required": [
          "id",
          "userId",
          "documentType",
          "transactionDate",
          "amount",
          "vendorName",
          "currencyCode",
          "fileHash",
          "originalFileName",
          "storageUrl",
          "createdAt",
          "updatedAt"
        ],
        "type": "object"
      },
      "EBookDocumentResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/EBookDocumentMetadata"
          },
          "message": {
            "example": "電子帳簿保存法対応: 文書を登録しました",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "EBookDocumentType": {
        "description": "Document type for Electronic Book Preservation Law classification",
        "enum": [
          "receipt",
          "invoice",
          "contract",
          "quotation",
          "delivery_slip",
          "bank_statement",
          "credit_card",
          "electronic_mail",
          "edi",
          "other"
        ],
        "example": "receipt",
        "type": "string"
      },
      "EBookHealthResponse": {
        "properties": {
          "features": {
            "example": [
              "Document registration with compliance metadata",
              "Timestamp management (タイムスタンプ)",
              "Searchable by date/amount/vendor (検索機能)",
              "Audit trail (訂正削除履歴)",
              "Compliance checking"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "message": {
            "example": "電子帳簿保存法 API is running",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "features"
        ],
        "type": "object"
      },
      "ETaxSessionResponse": {
        "properties": {
          "data": {
            "properties": {
              "expires_at": {
                "example": "2024-01-15T11:30:00.000Z",
                "format": "date-time",
                "type": "string"
              },
              "is_active": {
                "example": true,
                "type": "boolean"
              },
              "session_id": {
                "example": "sess_123456",
                "type": "string"
              },
              "user_id": {
                "example": "user123",
                "type": "string"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Session stored successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "type": "object"
      },
      "ETaxXMLResponse": {
        "properties": {
          "data": {
            "properties": {
              "document_type": {
                "example": "withholding-slip",
                "type": "string"
              },
              "generated_at": {
                "example": "2024-01-15T10:30:00.000Z",
                "format": "date-time",
                "type": "string"
              },
              "xml_content": {
                "example": "<?xml version=\"1.0\"...",
                "type": "string"
              },
              "year": {
                "example": 2024,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "XML document generated successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "type": "object"
      },
      "EligibilityResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/SimplifiedTaxationEligibility"
          },
          "message": {
            "example": "簡易課税を選択できます",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "Employee": {
        "properties": {
          "annualSalaryYtd": {
            "type": "number"
          },
          "annualTaxYtd": {
            "type": "number"
          },
          "baseSalary": {
            "type": "integer"
          },
          "companyId": {
            "format": "uuid",
            "type": "string"
          },
          "department": {
            "type": "string"
          },
          "employeeNumber": {
            "type": "string"
          },
          "employmentStatus": {
            "type": "string"
          },
          "executiveCompensation": {
            "type": "integer"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "isRepresentative": {
            "type": "boolean"
          },
          "isYearEndAdjustmentTarget": {
            "type": "boolean"
          },
          "joinDate": {
            "type": "integer"
          },
          "name": {
            "type": "string"
          },
          "nameKana": {
            "type": "string"
          },
          "positionTitle": {
            "type": "string"
          },
          "positionType": {
            "type": "string"
          },
          "userId": {
            "format": "uuid",
            "type": "string"
          }
        },
        "type": "object"
      },
      "EmployeeAnnualIncome": {
        "properties": {
          "adjustmentAmount": {
            "description": "Tax adjustment amount (過不足税額) - positive for refund, negative for additional collection",
            "example": 118100,
            "format": "decimal",
            "type": "number"
          },
          "calculatedTax": {
            "description": "算出所得税額 — 課税給与所得金額（千円未満切捨て）× 速算表, before 復興特別所得税",
            "example": 114400,
            "format": "decimal",
            "type": "number"
          },
          "deductions": {
            "$ref": "#/components/schemas/YearEndDeductions"
          },
          "employeeId": {
            "description": "Employee ID",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "employeeName": {
            "description": "Employee name",
            "example": "田中太郎",
            "type": "string"
          },
          "finalTax": {
            "description": "年調年税額 = taxAfterCredit × 102.1%（百円未満切捨て）",
            "example": 1900,
            "format": "decimal",
            "type": "number"
          },
          "grossIncome": {
            "description": "Total gross income (収入金額合計)",
            "example": 6000000,
            "format": "decimal",
            "type": "number"
          },
          "municipalTaxBase": {
            "description": "Municipal tax base amount (住民税課税標準額)",
            "example": 2119000,
            "format": "decimal",
            "type": "number"
          },
          "netSalaryIncome": {
            "description": "Net salary income after deduction (給与所得)",
            "example": 4360000,
            "format": "decimal",
            "type": "number"
          },
          "salaryIncomeDeduction": {
            "description": "Salary income deduction (給与所得控除)",
            "example": 1640000,
            "format": "decimal",
            "type": "number"
          },
          "taxAfterCredit": {
            "description": "年調所得税額 = calculatedTax − taxCredit",
            "example": 114400,
            "format": "decimal",
            "type": "number"
          },
          "taxCredit": {
            "description": "住宅借入金等特別控除額 (capped at calculatedTax)",
            "example": 0,
            "format": "decimal",
            "type": "number"
          },
          "taxableIncome": {
            "description": "Taxable income amount (課税所得金額)",
            "example": 2119000,
            "format": "decimal",
            "type": "number"
          },
          "totalBonus": {
            "description": "Total bonus for the year (賞与総額)",
            "example": 1000000,
            "format": "decimal",
            "type": "number"
          },
          "totalDeductions": {
            "description": "Total deductions amount (控除合計)",
            "example": 2241000,
            "format": "decimal",
            "type": "number"
          },
          "totalSalary": {
            "description": "Total salary for the year (給与総額)",
            "example": 5000000,
            "format": "decimal",
            "type": "number"
          },
          "withheldTax": {
            "description": "Total withheld tax for the year (源泉徴収税額)",
            "example": 120000,
            "format": "decimal",
            "type": "number"
          }
        },
        "required": [
          "employeeId",
          "employeeName",
          "totalSalary",
          "totalBonus",
          "grossIncome",
          "salaryIncomeDeduction",
          "netSalaryIncome",
          "deductions",
          "totalDeductions",
          "taxableIncome",
          "calculatedTax",
          "taxCredit",
          "taxAfterCredit",
          "finalTax",
          "withheldTax",
          "adjustmentAmount",
          "municipalTaxBase"
        ],
        "type": "object"
      },
      "EmployeeCount": {
        "description": "Expected number of employees",
        "enum": [
          "solo",
          "2to5",
          "6to10",
          "over10"
        ],
        "example": "2to5",
        "type": "string"
      },
      "EmployeeDeductionInput": {
        "properties": {
          "dependent_deduction": {
            "description": "Dependent deduction amount",
            "example": 380000,
            "format": "decimal",
            "type": "number"
          },
          "earthquake_insurance_deduction": {
            "description": "Earthquake insurance deduction amount",
            "example": 25000,
            "format": "decimal",
            "type": "number"
          },
          "housing_loan_deduction": {
            "description": "Housing loan tax credit amount",
            "example": 210000,
            "format": "decimal",
            "type": "number"
          },
          "ideco_deduction": {
            "description": "iDeCo contribution deduction amount",
            "example": 276000,
            "format": "decimal",
            "type": "number"
          },
          "life_insurance_deduction": {
            "description": "Life insurance deduction amount (if calculated separately)",
            "example": 40000,
            "format": "decimal",
            "type": "number"
          },
          "new_life_insurance": {
            "description": "New life insurance premium amount",
            "example": 80000,
            "format": "decimal",
            "type": "number"
          },
          "nursing_insurance": {
            "description": "Nursing care insurance premium amount",
            "example": 20000,
            "format": "decimal",
            "type": "number"
          },
          "old_life_insurance": {
            "description": "Old life insurance premium amount",
            "example": 0,
            "format": "decimal",
            "type": "number"
          },
          "small_business_mutual_aid_deduction": {
            "description": "Small business mutual aid deduction amount",
            "example": 120000,
            "format": "decimal",
            "type": "number"
          },
          "spouse_deduction": {
            "description": "Spouse deduction amount",
            "example": 380000,
            "format": "decimal",
            "type": "number"
          },
          "spouse_special_deduction": {
            "description": "Special spouse deduction amount",
            "example": 0,
            "format": "decimal",
            "type": "number"
          }
        },
        "type": "object"
      },
      "EmployeeDetailsResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/EmployeeAnnualIncome"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "EmployeeSummary": {
        "properties": {
          "adjustmentAmount": {
            "description": "Tax adjustment amount",
            "example": 118100,
            "format": "decimal",
            "type": "number"
          },
          "adjustmentType": {
            "$ref": "#/components/schemas/AdjustmentType"
          },
          "employeeName": {
            "description": "Employee name",
            "example": "田中太郎",
            "type": "string"
          },
          "finalTax": {
            "description": "Final annual tax amount",
            "example": 1900,
            "format": "decimal",
            "type": "number"
          },
          "grossIncome": {
            "description": "Total gross income",
            "example": 6000000,
            "format": "decimal",
            "type": "number"
          },
          "withheldTax": {
            "description": "Total withheld tax",
            "example": 120000,
            "format": "decimal",
            "type": "number"
          }
        },
        "required": [
          "employeeName",
          "grossIncome",
          "finalTax",
          "withheldTax",
          "adjustmentAmount",
          "adjustmentType"
        ],
        "type": "object"
      },
      "EmploymentDesign": {
        "properties": {
          "classification_path": {
            "type": "string"
          },
          "classification_severity": {
            "enum": [
              "ok",
              "warn",
              "block"
            ],
            "type": "string"
          },
          "created_at": {
            "format": "date-time",
            "type": "string"
          },
          "hire_id": {
            "format": "uuid",
            "type": "string"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "monthly_salary_yen": {
            "type": "integer"
          },
          "status": {
            "enum": [
              "draft",
              "blocked",
              "accepted"
            ],
            "type": "string"
          },
          "target_year": {
            "type": "integer"
          }
        },
        "type": "object"
      },
      "EnhancedAlert": {
        "properties": {
          "description": {
            "description": "Detailed explanation in Japanese",
            "example": "今後30日間のキャッシュフロー予測で資金不足が予想されます。売掛金の回収促進や支払いの調整を検討してください。",
            "type": "string"
          },
          "id": {
            "description": "Alert unique identifier",
            "example": "cash_flow_warning_001",
            "type": "string"
          },
          "level": {
            "$ref": "#/components/schemas/AlertLevel"
          },
          "message": {
            "description": "Alert message in English",
            "example": "Cash flow forecast shows potential shortage",
            "type": "string"
          },
          "messageJa": {
            "description": "Alert message in Japanese",
            "example": "キャッシュフロー予測で資金不足の可能性",
            "type": "string"
          },
          "metric": {
            "description": "Related metric name",
            "example": "cash_runway_days",
            "type": "string"
          },
          "priority": {
            "description": "Alert priority level",
            "enum": [
              "high",
              "medium",
              "low"
            ],
            "example": "high",
            "type": "string"
          },
          "recommendedAction": {
            "description": "Recommended action in Japanese",
            "example": "売掛金回収の促進、支払い条件の見直し",
            "nullable": true,
            "type": "string"
          },
          "relatedValue": {
            "description": "Related value display",
            "example": "23日",
            "type": "string"
          }
        },
        "required": [
          "id",
          "level",
          "message",
          "messageJa",
          "description",
          "metric",
          "relatedValue",
          "priority"
        ],
        "type": "object"
      },
      "EnhancedReminder": {
        "description": "Enhanced reminder with multi-action support for statutory tasks",
        "properties": {
          "actions": {
            "description": "Per-action details for statutory tasks",
            "items": {
              "$ref": "#/components/schemas/TaskAction"
            },
            "type": "array"
          },
          "day": {
            "example": 31,
            "type": "integer"
          },
          "description": {
            "description": "Detailed description",
            "example": "給与所得の源泉徴収票",
            "type": "string"
          },
          "id": {
            "description": "Reminder ID (UUID or system-generated)",
            "example": "system-withholding-tax-slip-2026",
            "type": "string"
          },
          "is_done": {
            "description": "Overall completion: true if ALL required actions done",
            "example": false,
            "type": "boolean"
          },
          "month": {
            "example": 1,
            "type": "integer"
          },
          "reminder_cycle": {
            "$ref": "#/components/schemas/ReminderCycle"
          },
          "reminder_type": {
            "$ref": "#/components/schemas/ReminderType"
          },
          "shortTitle": {
            "description": "Short title for compact UI",
            "example": "源泉徴収票",
            "type": "string"
          },
          "title": {
            "description": "Full reminder title",
            "example": "源泉徴収票",
            "type": "string"
          },
          "year": {
            "example": 2026,
            "type": "integer"
          }
        },
        "required": [
          "id",
          "title",
          "reminder_cycle",
          "reminder_type",
          "day",
          "month",
          "year",
          "is_done"
        ],
        "type": "object"
      },
      "EnhancedRemindersListResponse": {
        "properties": {
          "data": {
            "items": {
              "$ref": "#/components/schemas/EnhancedReminder"
            },
            "type": "array"
          },
          "message": {
            "example": "Enhanced reminders retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "EnhancedUsageStats": {
        "description": "Enhanced usage stats with optional Langfuse fields and source indicator",
        "properties": {
          "api_key_source_breakdown": {
            "additionalProperties": {
              "properties": {
                "cost": {
                  "type": "number"
                },
                "requests": {
                  "type": "integer"
                },
                "tokens": {
                  "type": "integer"
                }
              },
              "type": "object"
            },
            "type": "object"
          },
          "avg_score": {
            "description": "Average feedback score 0-1 (only when source=langfuse)",
            "example": 0.82,
            "nullable": true,
            "type": "number"
          },
          "error_count": {
            "description": "Error count (only when source=langfuse)",
            "example": 2,
            "nullable": true,
            "type": "integer"
          },
          "featureBreakdown": {
            "additionalProperties": {
              "properties": {
                "cost": {
                  "type": "number"
                },
                "requests": {
                  "type": "integer"
                },
                "tokens": {
                  "type": "integer"
                }
              },
              "type": "object"
            },
            "description": "Cost/token/request aggregation by product feature (advisor_chat, advisor_rag_retrieval, …). Present when group_by=feature. Null DB features keyed as \"other\".",
            "nullable": true,
            "type": "object"
          },
          "latency_p50_ms": {
            "description": "P50 latency in milliseconds (only when source=langfuse)",
            "example": 1250,
            "nullable": true,
            "type": "number"
          },
          "latency_p95_ms": {
            "description": "P95 latency in milliseconds (only when source=langfuse)",
            "example": 3800,
            "nullable": true,
            "type": "number"
          },
          "operation_breakdown": {
            "additionalProperties": {
              "properties": {
                "cost": {
                  "type": "number"
                },
                "requests": {
                  "type": "integer"
                },
                "tokens": {
                  "type": "integer"
                }
              },
              "type": "object"
            },
            "type": "object"
          },
          "source": {
            "description": "Data source: \"langfuse\" for actual costs, \"local\" for estimated from client_usage_tokens",
            "enum": [
              "langfuse",
              "local"
            ],
            "example": "langfuse",
            "type": "string"
          },
          "total_cost": {
            "description": "Actual cost when source=langfuse, estimated when source=local",
            "example": 23.45,
            "type": "number"
          },
          "total_requests": {
            "example": 42,
            "type": "integer"
          },
          "total_tokens": {
            "example": 15750,
            "type": "integer"
          }
        },
        "required": [
          "total_tokens",
          "total_requests",
          "total_cost",
          "operation_breakdown",
          "api_key_source_breakdown",
          "source"
        ],
        "type": "object"
      },
      "EnrichedDocument": {
        "description": "Document with file details from file_uploads table (v4.17)",
        "properties": {
          "createdAt": {
            "format": "date-time",
            "type": "string"
          },
          "documentName": {
            "type": "string"
          },
          "documentType": {
            "type": "string"
          },
          "fileName": {
            "description": "Display filename: 20251202_請求書.pdf",
            "type": "string"
          },
          "fileSize": {
            "description": "File size in bytes",
            "type": "integer"
          },
          "fileUploadId": {
            "description": "Reference to file_uploads",
            "format": "uuid",
            "type": "string"
          },
          "fileUrl": {
            "description": "Full storage URL",
            "type": "string"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "mimeType": {
            "description": "MIME type: application/pdf",
            "type": "string"
          },
          "name": {
            "type": "string"
          },
          "originalFileName": {
            "description": "Original upload name",
            "type": "string"
          },
          "source": {
            "enum": [
              "file_upload",
              "direct"
            ],
            "type": "string"
          },
          "thumbnailUrl": {
            "description": "Thumbnail endpoint URL",
            "type": "string"
          }
        },
        "type": "object"
      },
      "EnumItem": {
        "properties": {
          "accountCode": {
            "description": "Related account code (if applicable)",
            "example": "6100",
            "type": "string"
          },
          "code": {
            "description": "Enum code (if applicable)",
            "example": "DRAFT",
            "type": "string"
          },
          "color": {
            "description": "UI color code (for status types)",
            "example": "green",
            "type": "string"
          },
          "description": {
            "description": "Detailed description",
            "example": "編集可能な下書き状態",
            "type": "string"
          },
          "editable": {
            "description": "Whether item is editable (for status types)",
            "example": true,
            "type": "boolean"
          },
          "formula": {
            "description": "Calculation formula (for depreciation methods)",
            "example": "(取得価額 - 残存価額) / 耐用年数",
            "type": "string"
          },
          "frequency": {
            "description": "Frequency (for reminder types)",
            "example": "monthly",
            "type": "string"
          },
          "label": {
            "description": "Japanese label",
            "example": "下書き",
            "type": "string"
          },
          "labelEn": {
            "description": "English label",
            "example": "Draft",
            "type": "string"
          },
          "nextActions": {
            "description": "Available next actions (for workflow statuses)",
            "example": [
              "submit",
              "save"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "rate": {
            "description": "Rate value (for tax types, etc.)",
            "example": 0.1,
            "format": "double",
            "type": "number"
          },
          "usefulLife": {
            "description": "Useful life in years (for asset classifications)",
            "example": 5,
            "type": "integer"
          },
          "value": {
            "description": "Enum value (string or integer)",
            "example": "draft",
            "oneOf": [
              {
                "type": "string"
              },
              {
                "type": "integer"
              }
            ]
          },
          "withholdingRequired": {
            "description": "Whether withholding is required (for payee types)",
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "value",
          "label"
        ],
        "type": "object"
      },
      "EnumNotFoundResponse": {
        "properties": {
          "availableEnums": {
            "description": "List of available enum names",
            "example": [
              "expenseCategories",
              "documentTypes",
              "paymentMethods",
              "taxTypes",
              "withholdingCategories",
              "payeeTypes",
              "fiscalPeriodStatuses",
              "reconciliationStatuses",
              "expenseReportStatuses",
              "fixedAssetClassifications",
              "depreciationMethods",
              "journalEntryStatuses",
              "reminderTypes"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "data": {
            "example": null,
            "type": "null"
          },
          "message": {
            "example": "Enum 'invalidEnum' not found",
            "type": "string"
          },
          "success": {
            "example": false,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data",
          "availableEnums"
        ],
        "type": "object"
      },
      "EnumResponse": {
        "properties": {
          "data": {
            "items": {
              "$ref": "#/components/schemas/EnumItem"
            },
            "type": "array"
          },
          "message": {
            "example": "expenseCategoriesを取得しました",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "EnumValidationResult": {
        "properties": {
          "enumName": {
            "description": "Enum name that was validated",
            "example": "expenseCategories",
            "type": "string"
          },
          "label": {
            "description": "Label for the value (if valid)",
            "example": "下書き",
            "type": "string"
          },
          "valid": {
            "description": "Whether the value is valid",
            "example": true,
            "type": "boolean"
          },
          "value": {
            "description": "Value that was validated",
            "example": "draft",
            "oneOf": [
              {
                "type": "string"
              },
              {
                "type": "integer"
              }
            ]
          }
        },
        "required": [
          "valid",
          "enumName",
          "value"
        ],
        "type": "object"
      },
      "EnvVariablesResponse": {
        "properties": {
          "data": {
            "description": "Environment variables configuration",
            "type": "object"
          },
          "message": {
            "example": "Environment variables retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ErrorResponse": {
        "properties": {
          "error": {
            "properties": {
              "code": {
                "example": "AI_TIMEOUT",
                "type": "string"
              },
              "message": {
                "type": "string"
              },
              "messagePlain": {
                "type": "string"
              },
              "retryAfterMs": {
                "nullable": true,
                "type": "number"
              },
              "retryable": {
                "type": "boolean"
              },
              "suggestion": {
                "nullable": true,
                "type": "string"
              },
              "tone": {
                "enum": [
                  "apologetic",
                  "encouraging",
                  "informative"
                ],
                "type": "string"
              }
            },
            "type": "object"
          }
        },
        "type": "object"
      },
      "Establishment": {
        "properties": {
          "created_at": {
            "format": "date-time",
            "type": "string"
          },
          "entity_type": {
            "enum": [
              "kk",
              "gk",
              "sole_prop"
            ],
            "type": "string"
          },
          "headcount": {
            "type": "integer"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "name": {
            "type": "string"
          }
        },
        "type": "object"
      },
      "EstablishmentEventType": {
        "description": "Analytics event type for establishment tracking",
        "enum": [
          "guide_started",
          "step_started",
          "step_completed",
          "step_skipped",
          "ai_suggestion_requested",
          "ai_suggestion_applied",
          "ai_suggestion_dismissed",
          "document_generated",
          "guide_completed",
          "guide_abandoned"
        ],
        "example": "step_completed",
        "type": "string"
      },
      "EstablishmentProgress": {
        "properties": {
          "company_id": {
            "description": "Associated company ID for multi-company support",
            "example": "comp_123456",
            "type": "string"
          },
          "completed_at": {
            "description": "Guide completion timestamp",
            "example": "2024-01-20T16:00:00Z",
            "format": "date-time",
            "type": "string"
          },
          "completed_steps": {
            "description": "Array of completed step indices",
            "example": [
              0,
              1,
              2
            ],
            "items": {
              "maximum": 17,
              "minimum": 0,
              "type": "number"
            },
            "type": "array"
          },
          "current_step_index": {
            "description": "Current step index (0-17)",
            "example": 3,
            "maximum": 17,
            "minimum": 0,
            "type": "number"
          },
          "document_status": {
            "additionalProperties": {
              "$ref": "#/components/schemas/DocumentStatus"
            },
            "description": "Document generation status tracking",
            "example": {
              "articles_of_incorporation": {
                "document_type": "articles_of_incorporation",
                "generated_at": "2024-01-15T10:30:00Z",
                "status": "draft"
              }
            },
            "type": "object"
          },
          "last_updated": {
            "description": "Last update timestamp",
            "example": "2024-01-15T10:30:00Z",
            "format": "date-time",
            "type": "string"
          },
          "started_at": {
            "description": "Guide start timestamp",
            "example": "2024-01-15T09:00:00Z",
            "format": "date-time",
            "type": "string"
          },
          "step_data": {
            "additionalProperties": true,
            "description": "Step-specific data and user inputs",
            "example": {
              "BUSINESS_PURPOSE": {
                "purposes": [
                  "ソフトウェア開発",
                  "システム設計"
                ]
              },
              "COMPANY_TYPE": {
                "reasoning": "Better for funding",
                "selectedType": "kk"
              }
            },
            "type": "object"
          },
          "step_time_tracking": {
            "additionalProperties": {
              "$ref": "#/components/schemas/StepTimeTracking"
            },
            "description": "Time tracking for each step",
            "example": {
              "COMPANY_TYPE": {
                "completed_at": "2024-01-15T10:30:00Z",
                "started_at": "2024-01-15T10:00:00Z",
                "time_spent_ms": 1800000
              }
            },
            "type": "object"
          },
          "user_context": {
            "additionalProperties": true,
            "description": "Flexible user context object",
            "example": {
              "businessPurpose": "ソフトウェアの開発、販売及び保守",
              "businessType": "IT",
              "companyType": "kk"
            },
            "type": "object"
          }
        },
        "required": [
          "current_step_index",
          "completed_steps",
          "last_updated"
        ],
        "type": "object"
      },
      "EstablishmentStep": {
        "description": "Company establishment step identifier",
        "enum": [
          "COMPANY_TYPE",
          "BUSINESS_PURPOSE",
          "COMPANY_NAME",
          "VIRTUAL_OFFICE",
          "COMPANY_SEAL",
          "CAPITAL_PLANNING",
          "ARTICLES_OF_INCORPORATION",
          "CAPITAL_PAYMENT",
          "ELECTRONIC_CERTIFICATE",
          "REGISTRATION_APPLICATION",
          "SEAL_REGISTRATION",
          "LICENSES_PERMITS",
          "TAX_NOTIFICATIONS",
          "SOCIAL_INSURANCE",
          "CORPORATE_BANK_ACCOUNT",
          "ACCOUNTING_SETUP",
          "BUSINESS_CARDS_WEBSITE",
          "SUBSIDIES_GRANTS"
        ],
        "example": "BUSINESS_PURPOSE",
        "type": "string"
      },
      "EstablishmentUserContext": {
        "properties": {
          "businessPurpose": {
            "description": "Business purpose for articles of incorporation",
            "example": "ソフトウェアの開発、販売及び保守",
            "nullable": true,
            "type": "string"
          },
          "businessType": {
            "description": "Type of business",
            "example": "IT",
            "nullable": true,
            "type": "string"
          },
          "capitalAmount": {
            "description": "Capital amount in yen",
            "example": 1000000,
            "nullable": true,
            "type": "number"
          },
          "companyName": {
            "description": "Proposed company name",
            "example": "テクノロジー株式会社",
            "nullable": true,
            "type": "string"
          },
          "companyType": {
            "description": "Company type (kk: 株式会社, llc: 合同会社)",
            "enum": [
              "kk",
              "llc"
            ],
            "example": "kk",
            "nullable": true,
            "type": "string"
          },
          "foundersCount": {
            "description": "Number of founders",
            "example": 2,
            "nullable": true,
            "type": "number"
          },
          "prefecture": {
            "description": "Prefecture for business registration",
            "example": "東京都",
            "nullable": true,
            "type": "string"
          }
        },
        "type": "object"
      },
      "EstimateTaxRequest": {
        "properties": {
          "capitalAmount": {
            "example": 1000000,
            "type": "number"
          },
          "consumptionTaxMethod": {
            "enum": [
              "standard",
              "simplified"
            ],
            "example": "standard",
            "type": "string"
          },
          "expenses": {
            "example": 7200000,
            "type": "number"
          },
          "isConsumptionTaxRegistered": {
            "example": true,
            "type": "boolean"
          },
          "revenue": {
            "example": 12000000,
            "type": "number"
          }
        },
        "required": [
          "revenue",
          "expenses"
        ],
        "type": "object"
      },
      "ExchangeRate": {
        "properties": {
          "id": {
            "description": "Exchange rate unique identifier",
            "example": "789e0123-e45b-67c8-d901-234567890123",
            "format": "uuid",
            "type": "string"
          },
          "provider": {
            "description": "Exchange rate provider",
            "example": "Bank of Japan",
            "type": "string"
          },
          "rate": {
            "description": "Exchange rate value",
            "example": 150.25,
            "type": "number"
          },
          "source": {
            "description": "Currency pair (e.g., USD/JPY)",
            "example": "USD/JPY",
            "type": "string"
          }
        },
        "required": [
          "id",
          "source",
          "provider",
          "rate"
        ],
        "type": "object"
      },
      "ExchangeRateApplicationResponse": {
        "properties": {
          "data": {
            "properties": {
              "converted_amount": {
                "description": "Converted amount in Japanese Yen",
                "example": 15025,
                "type": "number"
              },
              "exchange_rate": {
                "description": "Applied exchange rate",
                "example": 150.25,
                "type": "number"
              },
              "exchange_rate_id": {
                "description": "Applied exchange rate identifier",
                "example": "789e0123-e45b-67c8-d901-234567890123",
                "format": "uuid",
                "type": "string"
              },
              "expense_id": {
                "description": "Updated expense identifier",
                "example": "123e4567-e89b-12d3-a456-426614174000",
                "format": "uuid",
                "type": "string"
              },
              "original_amount": {
                "description": "Original amount in foreign currency",
                "example": 100,
                "type": "number"
              }
            },
            "required": [
              "expense_id",
              "exchange_rate_id",
              "original_amount",
              "converted_amount",
              "exchange_rate"
            ],
            "type": "object"
          },
          "message": {
            "example": "Exchange rate applied successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ExchangeRateCollection": {
        "properties": {
          "base_currency": {
            "default": "JPY",
            "description": "Base currency for rate calculations",
            "example": "JPY",
            "type": "string"
          },
          "date": {
            "description": "Rate date in YYYYMMDD format",
            "example": 20240115,
            "maximum": 99991231,
            "minimum": 19000101,
            "type": "integer"
          },
          "last_updated": {
            "description": "When rates were last updated",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "rates": {
            "description": "Array of exchange rates for the specified date",
            "items": {
              "$ref": "#/components/schemas/ExchangeRate"
            },
            "type": "array"
          },
          "total_rates": {
            "description": "Total number of rates available for this date",
            "example": 15,
            "minimum": 0,
            "type": "integer"
          }
        },
        "required": [
          "date",
          "rates",
          "total_rates",
          "base_currency",
          "last_updated"
        ],
        "type": "object"
      },
      "ExchangeRateFetchResponse": {
        "properties": {
          "data": {
            "properties": {
              "cache_updated": {
                "description": "Whether local cache was updated",
                "example": true,
                "type": "boolean"
              },
              "fetched_from_external": {
                "description": "Whether rates were fetched from external API",
                "example": true,
                "type": "boolean"
              },
              "rates": {
                "$ref": "#/components/schemas/ExchangeRateCollection"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Exchange rates fetched successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ExchangeRateResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/ExchangeRateCollection"
          },
          "message": {
            "example": "Exchange rates retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ExecuteTestScriptRequest": {
        "properties": {
          "companyId": {
            "format": "uuid",
            "type": "string"
          },
          "dataContext": {
            "example": "backend",
            "type": "string"
          },
          "errors": {
            "items": {
              "properties": {
                "code": {
                  "type": "string"
                },
                "message": {
                  "type": "string"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "executionTimeMs": {
            "example": 1500,
            "type": "integer"
          },
          "inputRecordCount": {
            "example": 500,
            "type": "integer"
          },
          "integrityCheckRunId": {
            "description": "Link to integrity check if applicable",
            "format": "uuid",
            "type": "string"
          },
          "results": {
            "description": "Detailed execution results",
            "type": "object"
          },
          "scriptCategory": {
            "$ref": "#/components/schemas/TestScriptCategory"
          },
          "scriptId": {
            "example": "rebuild-trial-balance",
            "type": "string"
          },
          "scriptName": {
            "example": "試算表再構築",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          },
          "warnings": {
            "items": {
              "properties": {
                "code": {
                  "type": "string"
                },
                "message": {
                  "type": "string"
                }
              },
              "type": "object"
            },
            "type": "array"
          }
        },
        "required": [
          "scriptId",
          "scriptName",
          "success",
          "results"
        ],
        "type": "object"
      },
      "ExemptAsset": {
        "description": "Fixed asset NOT subject to 償却資産申告",
        "properties": {
          "acquisitionCost": {
            "example": 2945397,
            "type": "number"
          },
          "acquisitionDate": {
            "example": 20241201,
            "type": "integer"
          },
          "classification": {
            "example": 5,
            "type": "integer"
          },
          "classificationName": {
            "example": "車両運搬具",
            "type": "string"
          },
          "exemptCode": {
            "enum": [
              "BUILDING_REGISTERED",
              "VEHICLE_TAX",
              "LAND_REGISTERED",
              "INTANGIBLE_ASSET",
              "BELOW_MINIMUM",
              "REQUIRES_REVIEW"
            ],
            "example": "VEHICLE_TAX",
            "type": "string"
          },
          "exemptReason": {
            "example": "車両運搬具は自動車税で課税されるため対象外",
            "type": "string"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "name": {
            "example": "スズキ ジムニー シエラ",
            "type": "string"
          }
        },
        "type": "object"
      },
      "ExistingRule": {
        "properties": {
          "conditions": {
            "$ref": "#/components/schemas/ExistingRuleConditions"
          },
          "name": {
            "description": "Rule name",
            "example": "Amazon購入自動分類",
            "type": "string"
          }
        },
        "required": [
          "name",
          "conditions"
        ],
        "type": "object"
      },
      "ExistingRuleConditions": {
        "properties": {
          "amountRange": {
            "$ref": "#/components/schemas/AmountRange"
          },
          "descriptionContains": {
            "description": "Description keywords",
            "example": [
              "Amazon",
              "オフィス"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          }
        },
        "type": "object"
      },
      "ExpectedRevenue": {
        "description": "Expected annual revenue in 万円 (10,000 yen)",
        "enum": [
          "under500",
          "500to1000",
          "1000to3000",
          "over3000"
        ],
        "example": "1000to3000",
        "type": "string"
      },
      "Expense": {
        "properties": {
          "allocationRate": {
            "description": "Business allocation rate (0-1)",
            "example": 1,
            "nullable": true,
            "type": "number"
          },
          "amount": {
            "description": "Expense amount in original currency",
            "example": 5000,
            "nullable": true,
            "type": "number"
          },
          "attachments": {
            "description": "Attached receipts and documents",
            "items": {
              "$ref": "#/components/schemas/ExpenseAttachment"
            },
            "nullable": true,
            "type": "array"
          },
          "businessPurpose": {
            "description": "Detailed business purpose",
            "example": "Client meeting to discuss project requirements",
            "nullable": true,
            "type": "string"
          },
          "category": {
            "description": "Expense category (Japanese tax compliance)",
            "enum": [
              0,
              1,
              2,
              3,
              4,
              5,
              6,
              7,
              8,
              9,
              10,
              11,
              12,
              13,
              14,
              15,
              16,
              17,
              18,
              19,
              20,
              21,
              22,
              23,
              24,
              25,
              26
            ],
            "example": 1,
            "nullable": true,
            "type": "integer"
          },
          "companyPaid": {
            "description": "Whether expense was paid by company",
            "example": false,
            "nullable": true,
            "type": "boolean"
          },
          "currency": {
            "description": "Currency code (ISO 4217)",
            "example": "JPY",
            "nullable": true,
            "type": "string"
          },
          "date": {
            "description": "Expense date as Unix timestamp",
            "example": 1640995200,
            "nullable": true,
            "type": "integer"
          },
          "exchangeRate": {
            "$ref": "#/components/schemas/ExchangeRate",
            "nullable": true
          },
          "excludeFromReimbursement": {
            "description": "Whether to exclude from reimbursement",
            "example": false,
            "nullable": true,
            "type": "boolean"
          },
          "id": {
            "description": "Expense unique identifier",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "paymentMethod": {
            "description": "Payment method used",
            "enum": [
              0,
              1,
              2,
              3,
              4,
              5,
              6,
              7,
              8,
              9,
              10,
              11
            ],
            "example": 1,
            "nullable": true,
            "type": "integer"
          },
          "purpose": {
            "description": "Expense purpose or description",
            "example": "Business lunch with client",
            "nullable": true,
            "type": "string"
          },
          "remarks": {
            "description": "Additional remarks and notes",
            "example": [
              "Receipt attached",
              "Business purpose documented"
            ],
            "items": {
              "type": "string"
            },
            "nullable": true,
            "type": "array"
          },
          "taxCategory": {
            "description": "Japanese tax category",
            "enum": [
              1,
              2,
              3,
              4,
              5
            ],
            "example": 1,
            "nullable": true,
            "type": "integer"
          },
          "vendor": {
            "description": "Vendor or payee name",
            "example": "ABC Restaurant",
            "nullable": true,
            "type": "string"
          },
          "yenAmount": {
            "description": "Amount converted to Japanese Yen",
            "example": 5000,
            "nullable": true,
            "type": "number"
          }
        },
        "required": [
          "id"
        ],
        "type": "object"
      },
      "ExpenseAttachment": {
        "properties": {
          "id": {
            "description": "Attachment unique identifier",
            "example": "456e7890-f12a-34b5-c678-901234567890",
            "format": "uuid",
            "type": "string"
          },
          "name": {
            "description": "File name",
            "example": "receipt_20240115.pdf",
            "type": "string"
          },
          "type": {
            "description": "File MIME type",
            "example": "application/pdf",
            "type": "string"
          },
          "url": {
            "description": "File download URL",
            "example": "https://storage.example.com/receipts/receipt_20240115.pdf",
            "format": "uri",
            "type": "string"
          }
        },
        "required": [
          "id",
          "name",
          "url",
          "type"
        ],
        "type": "object"
      },
      "ExpenseAuditLog": {
        "allOf": [
          {
            "$ref": "#/components/schemas/AuditLogEntry"
          },
          {
            "properties": {
              "expense_id": {
                "description": "Referenced expense ID",
                "format": "uuid",
                "type": "string"
              }
            },
            "required": [
              "expense_id"
            ],
            "type": "object"
          }
        ],
        "description": "Audit log for expenses table. Added in v5.13. Triggers: INSERT, UPDATE, DELETE."
      },
      "ExpenseBreakdownItem": {
        "properties": {
          "amount": {
            "description": "Amount for this category",
            "example": 5000,
            "format": "decimal",
            "type": "number"
          },
          "category": {
            "description": "Expense category",
            "example": "交通費",
            "type": "string"
          },
          "taxCategory": {
            "description": "Tax category",
            "example": "課税仕入",
            "type": "string"
          }
        },
        "required": [
          "category",
          "amount"
        ],
        "type": "object"
      },
      "ExpenseCategoriesResponse": {
        "properties": {
          "count": {
            "description": "Number of expense categories",
            "example": 17,
            "type": "integer"
          },
          "data": {
            "items": {
              "$ref": "#/components/schemas/EnumItem"
            },
            "type": "array"
          },
          "message": {
            "example": "経費カテゴリを取得しました",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data",
          "count"
        ],
        "type": "object"
      },
      "ExpenseListResponse": {
        "properties": {
          "data": {
            "items": {
              "$ref": "#/components/schemas/Expense"
            },
            "type": "array"
          },
          "message": {
            "example": "Document expense retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ExpenseRemovalResponse": {
        "properties": {
          "data": {
            "properties": {
              "document_id": {
                "example": "456e7890-f12a-34b5-c678-901234567890",
                "format": "uuid",
                "type": "string"
              },
              "expense_id": {
                "example": "123e4567-e89b-12d3-a456-426614174000",
                "format": "uuid",
                "type": "string"
              },
              "removed": {
                "example": true,
                "type": "boolean"
              }
            },
            "required": [
              "removed",
              "expense_id",
              "document_id"
            ],
            "type": "object"
          },
          "message": {
            "example": "Expense removed from document successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ExpenseResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/Expense"
          },
          "message": {
            "example": "Expense updated successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ExpenseSyncResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/ExpenseSyncResult"
          },
          "message": {
            "example": "Expense synchronized successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ExpenseSyncResult": {
        "properties": {
          "expenseId": {
            "description": "ID of the synchronized expense",
            "example": "exp12345-6789-abcd-efgh-ijklmnopqrst",
            "format": "uuid",
            "type": "string"
          },
          "syncedToDocuments": {
            "description": "Documents the expense was synchronized to",
            "items": {
              "properties": {
                "documentId": {
                  "format": "uuid",
                  "type": "string"
                },
                "documentName": {
                  "type": "string"
                },
                "documentType": {
                  "type": "string"
                },
                "referenceRole": {
                  "enum": [
                    "report",
                    "claim",
                    "payment"
                  ],
                  "type": "string"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "totalSyncedReferences": {
            "description": "Total number of expense references created",
            "example": 2,
            "type": "integer"
          }
        },
        "required": [
          "expenseId",
          "syncedToDocuments",
          "totalSyncedReferences"
        ],
        "type": "object"
      },
      "ExportDataRequest": {
        "properties": {
          "data_types": {
            "description": "Types of data to export",
            "example": [
              "journal_entries"
            ],
            "items": {
              "$ref": "#/components/schemas/ExportDataType"
            },
            "minItems": 1,
            "type": "array"
          },
          "encoding": {
            "default": "utf8",
            "description": "Character encoding for CSV export",
            "enum": [
              "utf8",
              "shiftjis"
            ],
            "example": "utf8",
            "type": "string"
          },
          "end_date": {
            "description": "End date filter in YYYYMMDD format",
            "example": 20261231,
            "type": "integer"
          },
          "format": {
            "$ref": "#/components/schemas/ExportFormat"
          },
          "posted_only": {
            "default": true,
            "description": "Include only posted entries (default: true)",
            "example": true,
            "type": "boolean"
          },
          "start_date": {
            "description": "Start date filter in YYYYMMDD format",
            "example": 20260101,
            "type": "integer"
          },
          "target_software": {
            "$ref": "#/components/schemas/TargetSoftware",
            "description": "Target accounting software (optional, defaults to generic)"
          }
        },
        "required": [
          "data_types",
          "format"
        ],
        "type": "object"
      },
      "ExportDataResponse": {
        "properties": {
          "data": {
            "properties": {
              "content": {
                "description": "File content (UTF-8 for text, base64 for binary)",
                "example": "日付,伝票番号,摘要,勘定科目コード,...",
                "type": "string"
              },
              "content_type": {
                "description": "MIME type",
                "example": "text/csv; charset=utf-8",
                "type": "string"
              },
              "data_types": {
                "description": "Data types included in export",
                "example": [
                  "journal_entries"
                ],
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              "filename": {
                "description": "Generated filename",
                "example": "仕訳データ_yayoi_2026-01-30.csv",
                "type": "string"
              },
              "format": {
                "description": "Export format used",
                "example": "csv",
                "type": "string"
              },
              "record_count": {
                "description": "Number of records exported",
                "example": 150,
                "type": "integer"
              },
              "target_software": {
                "description": "Target software format",
                "example": "yayoi",
                "type": "string"
              }
            },
            "required": [
              "filename",
              "content",
              "content_type",
              "record_count",
              "data_types",
              "format"
            ],
            "type": "object"
          },
          "message": {
            "example": "150件のデータをエクスポートしました (Exported 150 records)",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ExportDataType": {
        "description": "Type of data to export",
        "enum": [
          "journal_entries",
          "trial_balance",
          "accounts",
          "clients"
        ],
        "example": "journal_entries",
        "type": "string"
      },
      "ExportFormat": {
        "description": "Export file format",
        "enum": [
          "csv",
          "json",
          "xlsx"
        ],
        "example": "csv",
        "type": "string"
      },
      "ExtractDocumentTemplateBody": {
        "description": "Provide either a file upload (multipart) or a text description",
        "properties": {
          "description": {
            "example": "取引先名、作業日、作業内容、金額の4項目がある報告書",
            "type": "string"
          }
        },
        "type": "object"
      },
      "ExtractedCompanyInfo": {
        "description": "v4.38: Enhanced with extended fields from 定款 for comprehensive extraction",
        "properties": {
          "businessObjectives": {
            "description": "Extracted business objectives (事業目的/目的) from article4.objectives. Array of all purposes.",
            "example": [
              "ソフトウェアの開発・販売・保守",
              "ITコンサルティング業",
              "Webサイトの企画、制作、運営",
              "上記に附帯する一切の業務"
            ],
            "items": {
              "type": "string"
            },
            "nullable": true,
            "type": "array"
          },
          "capital": {
            "description": "Extracted company capital in yen (資本金)",
            "example": 1000000,
            "format": "decimal",
            "type": "number"
          },
          "companyName": {
            "description": "Extracted company name (商号)",
            "example": "株式会社ソロボス",
            "type": "string"
          },
          "executiveCompensation": {
            "description": "Extracted monthly executive compensation (役員報酬) in yen from article17. e.g., \"月額２０万円\" → 200000",
            "example": 200000,
            "nullable": true,
            "type": "integer"
          },
          "firstFiscalYearEnd": {
            "description": "Extracted first fiscal year end (最初の事業年度末) in YYYYMMDD format from article31",
            "example": 20260215,
            "nullable": true,
            "type": "integer"
          },
          "fiscalYearEnd": {
            "description": "Extracted fiscal year end in YYYYMMDD format (事業年度終了)",
            "example": 20260331,
            "type": "integer"
          },
          "fiscalYearStart": {
            "description": "Extracted fiscal year start in YYYYMMDD format (事業年度開始)",
            "example": 20250401,
            "type": "integer"
          },
          "incorporationDate": {
            "description": "Extracted incorporation date (開業日) from 定款 signature.date field in YYYYMMDD format",
            "example": 20250606,
            "nullable": true,
            "type": "integer"
          },
          "memberInfo": {
            "description": "Extracted member/shareholder information (社員・出資情報)",
            "nullable": true,
            "properties": {
              "members": {
                "items": {
                  "properties": {
                    "address": {
                      "description": "Member address",
                      "example": "東京都渋谷区渋谷1-1-1",
                      "type": "string"
                    },
                    "capitalContribution": {
                      "description": "Capital contribution in yen",
                      "example": 1000000,
                      "type": "number"
                    },
                    "name": {
                      "description": "Member name",
                      "example": "田中太郎",
                      "type": "string"
                    }
                  },
                  "type": "object"
                },
                "type": "array"
              },
              "totalCapital": {
                "description": "Total capital from all members",
                "example": 1000000,
                "type": "number"
              }
            },
            "type": "object"
          },
          "officeAddress": {
            "description": "Extracted office address (本店の所在地)",
            "example": "東京都渋谷区渋谷1-1-1",
            "type": "string"
          },
          "publicNoticeMethod": {
            "description": "Extracted public notice method (公告方法) from article3. e.g., \"官報に掲載してする\"",
            "example": "官報に掲載してする",
            "nullable": true,
            "type": "string"
          },
          "representative": {
            "description": "Extracted representative name (代表社員)",
            "example": "田中太郎",
            "type": "string"
          }
        },
        "required": [
          "companyName",
          "fiscalYearStart",
          "fiscalYearEnd",
          "capital",
          "representative",
          "officeAddress"
        ],
        "type": "object"
      },
      "ExtractedCompanyInfoResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/ExtractedCompanyInfo"
          },
          "message": {
            "example": "Company information extracted successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ExtractedSkeleton": {
        "properties": {
          "fields": {
            "items": {
              "type": "object"
            },
            "type": "array"
          },
          "sections": {
            "items": {
              "type": "object"
            },
            "type": "array"
          }
        },
        "type": "object"
      },
      "FamilyHire": {
        "properties": {
          "created_at": {
            "format": "date-time",
            "type": "string"
          },
          "establishment_id": {
            "format": "uuid",
            "type": "string"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "name": {
            "type": "string"
          },
          "relation": {
            "enum": [
              "spouse",
              "child",
              "parent",
              "other"
            ],
            "type": "string"
          },
          "start_date": {
            "format": "date",
            "type": "string"
          },
          "visa_category": {
            "nullable": true,
            "type": "string"
          }
        },
        "type": "object"
      },
      "FileDeleteResponse": {
        "properties": {
          "data": {
            "properties": {
              "deletedFileId": {
                "example": "123e4567-e89b-12d3-a456-426614174000",
                "format": "uuid",
                "type": "string"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "File deleted successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "FileDocumentLink": {
        "properties": {
          "created_at": {
            "format": "date-time",
            "type": "string"
          },
          "created_by": {
            "format": "uuid",
            "type": "string"
          },
          "document_id": {
            "format": "uuid",
            "type": "string"
          },
          "file_id": {
            "format": "uuid",
            "type": "string"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "link_type": {
            "enum": [
              "attachment",
              "source",
              "source_receipt",
              "evidence",
              "supporting"
            ],
            "example": "source",
            "type": "string"
          }
        },
        "type": "object"
      },
      "FileGroupFullResponse": {
        "properties": {
          "data": {
            "allOf": [
              {
                "$ref": "#/components/schemas/FileUploadGroup"
              },
              {
                "properties": {
                  "document": {
                    "nullable": true,
                    "properties": {
                      "document_name": {
                        "type": "string"
                      },
                      "document_type": {
                        "type": "string"
                      },
                      "id": {
                        "format": "uuid",
                        "type": "string"
                      },
                      "status": {
                        "type": "string"
                      }
                    },
                    "type": "object"
                  },
                  "files": {
                    "items": {
                      "properties": {
                        "ai_data": {
                          "nullable": true,
                          "type": "object"
                        },
                        "confirmed_data": {
                          "nullable": true,
                          "type": "object"
                        },
                        "created_at": {
                          "format": "date-time",
                          "type": "string"
                        },
                        "file_name": {
                          "type": "string"
                        },
                        "file_type": {
                          "type": "string"
                        },
                        "file_url": {
                          "type": "string"
                        },
                        "id": {
                          "format": "uuid",
                          "type": "string"
                        }
                      },
                      "type": "object"
                    },
                    "type": "array"
                  }
                },
                "type": "object"
              }
            ]
          },
          "message": {
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "type": "object"
      },
      "FileListResponse": {
        "properties": {
          "data": {
            "items": {
              "$ref": "#/components/schemas/FileUpload"
            },
            "type": "array"
          },
          "message": {
            "example": "Files retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "FileMoveResponse": {
        "properties": {
          "data": {
            "properties": {
              "folderId": {
                "example": "456e7890-f12a-34b5-c678-901234567890",
                "format": "uuid",
                "type": "string"
              },
              "movedFiles": {
                "example": 3,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Files moved to folder successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "FileSearchHit": {
        "properties": {
          "analysisStatus": {
            "example": "completed",
            "nullable": true,
            "type": "string"
          },
          "counterpartyName": {
            "example": "農事組合法人干俣牧場組合",
            "nullable": true,
            "type": "string"
          },
          "createdAt": {
            "example": "2026-04-17T00:00:00.000Z",
            "nullable": true,
            "type": "string"
          },
          "docClass": {
            "example": "lease",
            "nullable": true,
            "type": "string"
          },
          "docClassSource": {
            "example": "ai",
            "nullable": true,
            "type": "string"
          },
          "fileId": {
            "format": "uuid",
            "type": "string"
          },
          "fileName": {
            "example": "事業用賃貸借契約書.pdf",
            "nullable": true,
            "type": "string"
          },
          "href": {
            "description": "In-app deep link that opens this file in the detail pane.",
            "example": "/files?file=d5966db8-654d-4fad-8ed2-af0cb2b55cb6",
            "type": "string"
          },
          "lexicalRank": {
            "example": 1,
            "nullable": true,
            "type": "integer"
          },
          "score": {
            "description": "RRF fused score.",
            "example": 0.0328,
            "type": "number"
          },
          "semanticRank": {
            "example": 2,
            "nullable": true,
            "type": "integer"
          },
          "semanticSimilarity": {
            "description": "Cosine similarity on the semantic leg; null when that leg did not match.",
            "example": 0.617,
            "nullable": true,
            "type": "number"
          },
          "snippet": {
            "description": "Window of search_text around the match, for result display.",
            "example": "…事業用賃貸借契約書 | 農事組合法人干俣牧場組合 | 月額 230,000円…",
            "type": "string"
          },
          "totalAmount": {
            "description": "取引金額 as printed, in totalCurrency.",
            "example": 253000,
            "nullable": true,
            "type": "number"
          },
          "totalAmountJpy": {
            "description": "totalAmount in yen at the receipt date's stored rate; null when foreign and no rate exists.",
            "example": 253000,
            "nullable": true,
            "type": "number"
          },
          "totalCurrency": {
            "description": "ISO currency of totalAmount; null when the analysis could not determine it.",
            "example": "JPY",
            "nullable": true,
            "type": "string"
          },
          "transactionDate": {
            "example": "2025-04-01",
            "nullable": true,
            "type": "string"
          }
        },
        "required": [
          "fileId",
          "href",
          "score"
        ],
        "type": "object"
      },
      "FileStatistics": {
        "properties": {
          "filesByStatus": {
            "description": "File count breakdown by processing status",
            "properties": {
              "processed": {
                "example": 80,
                "type": "integer"
              },
              "storage": {
                "example": 45,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "filesByType": {
            "description": "File count breakdown by type",
            "properties": {
              "docx": {
                "example": 10,
                "type": "integer"
              },
              "image": {
                "example": 85,
                "type": "integer"
              },
              "pdf": {
                "example": 30,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "totalFiles": {
            "description": "Total number of files for the user",
            "example": 125,
            "type": "integer"
          },
          "totalStorageUsed": {
            "description": "Total storage used in bytes",
            "example": 52428800,
            "type": "number"
          },
          "unsettledFiles": {
            "description": "Number of files not yet processed or confirmed",
            "example": 15,
            "type": "integer"
          }
        },
        "required": [
          "totalFiles",
          "filesByType",
          "filesByStatus",
          "totalStorageUsed",
          "unsettledFiles"
        ],
        "type": "object"
      },
      "FileStatisticsResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/FileStatistics"
          },
          "message": {
            "example": "File statistics retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "FileUpload": {
        "properties": {
          "ai_data": {
            "description": "AI-extracted data from file analysis",
            "properties": {
              "amount": {
                "example": 1250,
                "type": "number"
              },
              "categories": {
                "example": [
                  "receipt",
                  "restaurant"
                ],
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              "confidence": {
                "example": 0.95,
                "type": "number"
              },
              "date": {
                "example": "2024-01-15",
                "format": "date",
                "type": "string"
              },
              "extractedText": {
                "example": "Receipt from Restaurant ABC...",
                "type": "string"
              }
            },
            "type": "object"
          },
          "bucket": {
            "description": "Supabase storage bucket name",
            "example": "invoices",
            "type": "string"
          },
          "confirmed_data": {
            "description": "User-confirmed data after AI processing",
            "properties": {
              "amount": {
                "example": 1250,
                "type": "number"
              },
              "category": {
                "example": "business_meal",
                "type": "string"
              },
              "date": {
                "example": "2024-01-15",
                "format": "date",
                "type": "string"
              },
              "vendor": {
                "example": "Restaurant ABC",
                "type": "string"
              }
            },
            "type": "object"
          },
          "created_at": {
            "description": "File upload creation timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "file_metadata": {
            "description": "File metadata including storage information",
            "properties": {
              "bucketName": {
                "example": "invoices",
                "type": "string"
              },
              "filePath": {
                "example": "user123/receipt_2024_01_15_1705312200000.jpg",
                "type": "string"
              },
              "fileSize": {
                "example": 1048576,
                "type": "number"
              },
              "originalFileName": {
                "example": "receipt_2024_01_15.jpg",
                "type": "string"
              },
              "sanitizedFileName": {
                "example": "receipt_2024_01_15_1705312200000.jpg",
                "type": "string"
              }
            },
            "type": "object"
          },
          "file_name": {
            "description": "Original file name as uploaded",
            "example": "receipt_2024_01_15.jpg",
            "type": "string"
          },
          "file_type": {
            "description": "File type classification based on MIME type. xml / csv / zip are data files (e-Gov 公文書 and CSV evidence, notice-archive members): served as downloads only and never OCR-analyzed.",
            "enum": [
              "image",
              "pdf",
              "docx",
              "xml",
              "csv",
              "zip"
            ],
            "example": "image",
            "type": "string"
          },
          "file_url": {
            "description": "Supabase storage public URL for the file",
            "example": "https://supabase.co/storage/v1/object/public/invoices/user123/sanitized_receipt_20240115.jpg",
            "format": "uri",
            "type": "string"
          },
          "folder_id": {
            "description": "Folder identifier for file organization",
            "example": "456e7890-f12a-34b5-c678-901234567890",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "id": {
            "description": "File upload unique identifier",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "is_deleted": {
            "description": "Soft deletion flag",
            "example": false,
            "type": "boolean"
          },
          "status": {
            "description": "File processing status (storage: uploaded, processed: AI processed)",
            "enum": [
              "storage",
              "processed"
            ],
            "example": "storage",
            "type": "string"
          },
          "updated_at": {
            "description": "Last update timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "user_id": {
            "description": "User identifier who uploaded the file",
            "example": "789e0123-e45b-67c8-d901-234567890123",
            "format": "uuid",
            "type": "string"
          }
        },
        "required": [
          "id",
          "user_id",
          "file_name",
          "file_url",
          "bucket",
          "file_type",
          "status",
          "created_at",
          "updated_at"
        ],
        "type": "object"
      },
      "FileUploadGroup": {
        "properties": {
          "created_at": {
            "format": "date-time",
            "type": "string"
          },
          "description": {
            "nullable": true,
            "type": "string"
          },
          "document_id": {
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "file_count": {
            "example": 3,
            "type": "integer"
          },
          "group_type": {
            "enum": [
              "manual",
              "ai_suggested",
              "auto_session"
            ],
            "example": "manual",
            "type": "string"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "label": {
            "example": "1月の領収書",
            "type": "string"
          },
          "source_session_id": {
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "status": {
            "enum": [
              "pending",
              "confirmed",
              "archived"
            ],
            "example": "pending",
            "type": "string"
          },
          "target_document_type": {
            "example": "claims",
            "nullable": true,
            "type": "string"
          },
          "total_amount": {
            "description": "Integer JPY",
            "example": 5500,
            "nullable": true,
            "type": "integer"
          },
          "updated_at": {
            "format": "date-time",
            "type": "string"
          },
          "user_id": {
            "format": "uuid",
            "type": "string"
          }
        },
        "type": "object"
      },
      "FileUploadJob": {
        "properties": {
          "aiData": {
            "description": "AI-extracted data from file analysis",
            "properties": {
              "categories": {
                "example": [
                  "receipt",
                  "restaurant"
                ],
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              "confidence": {
                "example": 0.95,
                "type": "number"
              },
              "extractedText": {
                "example": "Receipt from Restaurant ABC...",
                "type": "string"
              }
            },
            "type": "object"
          },
          "completedAt": {
            "description": "Upload completion timestamp",
            "example": "2024-01-15T10:35:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "confirmedData": {
            "description": "User-confirmed data after AI processing",
            "properties": {
              "amount": {
                "example": 1250,
                "type": "number"
              },
              "date": {
                "example": "2024-01-15",
                "format": "date",
                "type": "string"
              },
              "vendor": {
                "example": "Restaurant ABC",
                "type": "string"
              }
            },
            "type": "object"
          },
          "confirmedFileName": {
            "description": "User-confirmed file name for storage",
            "example": "restaurant_receipt_2024_01_15.jpg",
            "type": "string"
          },
          "createdAt": {
            "description": "Upload job creation timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "error": {
            "description": "Error message if upload failed",
            "example": "Storage quota exceeded",
            "type": "string"
          },
          "fileUploadId": {
            "description": "The file_uploads row created for this upload (also on the file_upload_completed SSE event).",
            "format": "uuid",
            "type": "string"
          },
          "id": {
            "description": "Upload job unique identifier",
            "example": "456e7890-f12a-34b5-c678-901234567890",
            "format": "uuid",
            "type": "string"
          },
          "mimeType": {
            "description": "File MIME type",
            "example": "image/jpeg",
            "type": "string"
          },
          "originalFileName": {
            "description": "Original file name before processing",
            "example": "receipt_scan.jpg",
            "type": "string"
          },
          "status": {
            "description": "Upload job status",
            "enum": [
              "pending",
              "uploading",
              "completed",
              "failed"
            ],
            "example": "completed",
            "type": "string"
          },
          "supabaseUrl": {
            "description": "Supabase storage URL after successful upload",
            "example": "https://supabase.co/storage/v1/object/public/uploads/user123/receipt_2024.jpg",
            "format": "uri",
            "type": "string"
          },
          "uploadProgress": {
            "description": "Upload progress percentage",
            "example": 100,
            "maximum": 100,
            "minimum": 0,
            "type": "number"
          }
        },
        "required": [
          "id",
          "originalFileName",
          "confirmedFileName",
          "mimeType",
          "status",
          "uploadProgress",
          "createdAt"
        ],
        "type": "object"
      },
      "FileUploadResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/FileUpload"
          },
          "message": {
            "example": "File upload created successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 201,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "FiledReturnFigures": {
        "additionalProperties": false,
        "description": "view=figures: the key boxes each pinned return carries (年度比較) — read off the transmitted return, no recomputation",
        "properties": {
          "figures": {
            "description": "Only the boxes the return carries; a missing box is absent, never zero",
            "items": {
              "additionalProperties": false,
              "properties": {
                "box": {
                  "description": "XTX / eLTAX box id, e.g. BGB00010",
                  "type": "string"
                },
                "key": {
                  "enum": [
                    "taxableIncome",
                    "corporateTax",
                    "localCorporateTax",
                    "inhabitantTax",
                    "enterpriseTax",
                    "specialEnterpriseTax",
                    "consumptionTaxTotal"
                  ],
                  "type": "string"
                },
                "value": {
                  "description": "Yen; a 消費税 refund is negative",
                  "type": "number"
                }
              },
              "required": [
                "key",
                "value",
                "box"
              ],
              "type": "object"
            },
            "type": "array"
          },
          "filedReturnId": {
            "format": "uuid",
            "type": "string"
          },
          "filingType": {
            "type": "string"
          },
          "fiscalYear": {
            "type": "integer"
          },
          "periodEnd": {
            "description": "YYYYMMDD",
            "type": "integer"
          },
          "periodStart": {
            "description": "YYYYMMDD",
            "type": "integer"
          },
          "receiptNumber": {
            "nullable": true,
            "type": "string"
          },
          "sourceKind": {
            "description": "session_xml is SBC’s own file, not a filed value (ADR-0012)",
            "enum": [
              "received_data",
              "external_filing_snapshot",
              "session_xml"
            ],
            "type": "string"
          },
          "transmittedAt": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          }
        },
        "required": [
          "filedReturnId",
          "fiscalYear",
          "filingType",
          "periodStart",
          "periodEnd",
          "sourceKind",
          "figures"
        ],
        "type": "object"
      },
      "FiledReturnFiguresListResult": {
        "properties": {
          "data": {
            "properties": {
              "returns": {
                "items": {
                  "$ref": "#/components/schemas/FiledReturnFigures"
                },
                "type": "array"
              }
            },
            "required": [
              "returns"
            ],
            "type": "object"
          },
          "success": {
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "FiledReturnPeriod": {
        "additionalProperties": false,
        "description": "view=periods: which periods are filed — no ledger / consumption-tax recomputation",
        "properties": {
          "filedReturnId": {
            "format": "uuid",
            "type": "string"
          },
          "filingType": {
            "type": "string"
          },
          "fiscalYear": {
            "type": "integer"
          },
          "periodEnd": {
            "description": "YYYYMMDD",
            "type": "integer"
          },
          "periodStart": {
            "description": "YYYYMMDD",
            "type": "integer"
          },
          "receiptNumber": {
            "nullable": true,
            "type": "string"
          },
          "transmittedAt": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          }
        },
        "required": [
          "filedReturnId",
          "fiscalYear",
          "filingType",
          "periodStart",
          "periodEnd"
        ],
        "type": "object"
      },
      "FiledReturnPeriodsListResult": {
        "properties": {
          "data": {
            "properties": {
              "returns": {
                "items": {
                  "$ref": "#/components/schemas/FiledReturnPeriod"
                },
                "type": "array"
              }
            },
            "required": [
              "returns"
            ],
            "type": "object"
          },
          "success": {
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "FiledReturnPinResult": {
        "properties": {
          "data": {
            "properties": {
              "filedReturnId": {
                "format": "uuid",
                "type": "string"
              },
              "filingType": {
                "type": "string"
              },
              "fiscalYear": {
                "type": "integer"
              },
              "lineCount": {
                "type": "integer"
              },
              "sessionId": {
                "format": "uuid",
                "type": "string"
              },
              "snapshot": {
                "properties": {
                  "asOf": {
                    "format": "date-time",
                    "type": "string"
                  },
                  "asOfSource": {
                    "enum": [
                      "explicit",
                      "receipt",
                      "submitted_at",
                      "now"
                    ],
                    "type": "string"
                  },
                  "entryCount": {
                    "type": "integer"
                  },
                  "lineCount": {
                    "type": "integer"
                  },
                  "method": {
                    "type": "string"
                  },
                  "profitBeforeTax": {
                    "type": "number"
                  },
                  "uncertainEntries": {
                    "items": {
                      "type": "string"
                    },
                    "type": "array"
                  }
                },
                "type": "object"
              },
              "sourceKind": {
                "type": "string"
              }
            },
            "required": [
              "filedReturnId",
              "sessionId",
              "filingType",
              "fiscalYear",
              "sourceKind",
              "lineCount",
              "snapshot"
            ],
            "type": "object"
          },
          "success": {
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "FiledReturnRestorePreview": {
        "properties": {
          "data": {
            "description": "「申告時点に戻す」 dry run (BE ADR-0029): what the restore would change so the books equal the as-filed pin",
            "properties": {
              "accounts": {
                "items": {
                  "properties": {
                    "accountCode": {
                      "type": "string"
                    },
                    "accountName": {
                      "type": "string"
                    },
                    "currentAmount": {
                      "type": "number"
                    },
                    "delta": {
                      "description": "the restore’s effect on the account",
                      "type": "number"
                    },
                    "filedAmount": {
                      "description": "net debit − credit at filing",
                      "type": "number"
                    }
                  },
                  "type": "object"
                },
                "type": "array"
              },
              "actions": {
                "items": {
                  "properties": {
                    "createdAt": {
                      "format": "date-time",
                      "nullable": true,
                      "type": "string"
                    },
                    "currentAmount": {
                      "type": "number"
                    },
                    "currentStatus": {
                      "type": "string"
                    },
                    "description": {
                      "nullable": true,
                      "type": "string"
                    },
                    "entryDate": {
                      "type": "integer"
                    },
                    "entryNumber": {
                      "type": "string"
                    },
                    "journalEntryId": {
                      "format": "uuid",
                      "type": "string"
                    },
                    "kind": {
                      "enum": [
                        "void_created",
                        "restore_state",
                        "restore_lines",
                        "repost"
                      ],
                      "type": "string"
                    },
                    "lineChanges": {
                      "items": {
                        "properties": {
                          "from": {
                            "nullable": true,
                            "type": "object"
                          },
                          "journalEntryLineId": {
                            "format": "uuid",
                            "type": "string"
                          },
                          "to": {
                            "nullable": true,
                            "type": "object"
                          }
                        },
                        "type": "object"
                      },
                      "type": "array"
                    },
                    "profitEffect": {
                      "description": "税引前利益 change the action makes",
                      "type": "number"
                    },
                    "targetAmount": {
                      "type": "number"
                    },
                    "targetStatus": {
                      "description": "posted / reversed / draft / deleted",
                      "type": "string"
                    }
                  },
                  "required": [
                    "kind",
                    "journalEntryId",
                    "entryNumber",
                    "entryDate",
                    "currentStatus",
                    "targetStatus"
                  ],
                  "type": "object"
                },
                "type": "array"
              },
              "alreadyAsFiled": {
                "type": "boolean"
              },
              "asOf": {
                "description": "The pin instant (transmission)",
                "format": "date-time",
                "type": "string"
              },
              "blockers": {
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              "confirmationToken": {
                "description": "sha256 of the plan and live ledger; pass to apply",
                "nullable": true,
                "type": "string"
              },
              "filedReturnId": {
                "format": "uuid",
                "type": "string"
              },
              "filingType": {
                "type": "string"
              },
              "fiscalYear": {
                "type": "integer"
              },
              "periodEnd": {
                "description": "YYYYMMDD",
                "type": "integer"
              },
              "periodStart": {
                "description": "YYYYMMDD",
                "type": "integer"
              },
              "profitBeforeTax": {
                "properties": {
                  "afterRestore": {
                    "type": "number"
                  },
                  "current": {
                    "type": "number"
                  },
                  "filed": {
                    "type": "number"
                  }
                },
                "type": "object"
              },
              "snapshotId": {
                "format": "uuid",
                "type": "string"
              }
            },
            "required": [
              "filedReturnId",
              "periodStart",
              "periodEnd",
              "asOf",
              "alreadyAsFiled",
              "actions",
              "accounts",
              "profitBeforeTax",
              "blockers",
              "confirmationToken"
            ],
            "type": "object"
          },
          "success": {
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "FiledReturnRestoreResult": {
        "properties": {
          "data": {
            "properties": {
              "alreadyAsFiled": {
                "type": "boolean"
              },
              "applied": {
                "type": "boolean"
              },
              "counts": {
                "properties": {
                  "repost": {
                    "type": "integer"
                  },
                  "restoreLines": {
                    "type": "integer"
                  },
                  "restoreState": {
                    "type": "integer"
                  },
                  "voidCreated": {
                    "type": "integer"
                  }
                },
                "type": "object"
              },
              "filedReturnId": {
                "format": "uuid",
                "type": "string"
              },
              "findingsResolved": {
                "type": "integer"
              },
              "restoredAt": {
                "format": "date-time",
                "type": "string"
              },
              "verification": {
                "properties": {
                  "accountsMatch": {
                    "type": "boolean"
                  },
                  "ledgerMatches": {
                    "type": "boolean"
                  },
                  "linesMatch": {
                    "type": "boolean"
                  },
                  "profitBeforeTax": {
                    "type": "number"
                  }
                },
                "type": "object"
              }
            },
            "required": [
              "filedReturnId",
              "applied",
              "alreadyAsFiled",
              "counts",
              "verification"
            ],
            "type": "object"
          },
          "success": {
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "FiledReturnSummary": {
        "properties": {
          "currentValue": {
            "description": "現在 — the same figure recomputed from today’s ledger; null when no engine exists (地方税)",
            "nullable": true,
            "type": "number"
          },
          "delta": {
            "nullable": true,
            "type": "number"
          },
          "filedReturnId": {
            "format": "uuid",
            "type": "string"
          },
          "filedValue": {
            "description": "申告時 — the transmitted return’s headline figure",
            "nullable": true,
            "type": "number"
          },
          "filedValueLabel": {
            "description": "XTX box the 申告時 figure was read from",
            "type": "string"
          },
          "filingType": {
            "type": "string"
          },
          "fiscalYear": {
            "type": "integer"
          },
          "lastComputedAt": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "mirrorOfFiledReturnId": {
            "description": "Set on a 地方税 pin whose period equals the 法人税 pin of the same year: its ledger drift is the 法人税 drift (所得連動), so no findings are kept for it",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "openFindings": {
            "type": "integer"
          },
          "periodEnd": {
            "description": "YYYYMMDD",
            "type": "integer"
          },
          "periodStart": {
            "description": "YYYYMMDD",
            "type": "integer"
          },
          "receiptNumber": {
            "nullable": true,
            "type": "string"
          },
          "sessionId": {
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "snapshot": {
            "nullable": true,
            "properties": {
              "asOf": {
                "format": "date-time",
                "type": "string"
              },
              "entryCount": {
                "type": "integer"
              },
              "method": {
                "enum": [
                  "live",
                  "reconstructed_from_audit"
                ],
                "type": "string"
              },
              "profitBeforeTax": {
                "nullable": true,
                "type": "number"
              }
            },
            "type": "object"
          },
          "sourceKind": {
            "enum": [
              "received_data",
              "external_filing_snapshot",
              "session_xml"
            ],
            "type": "string"
          },
          "transmittedAt": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          }
        },
        "required": [
          "filedReturnId",
          "fiscalYear",
          "filingType",
          "sourceKind",
          "periodStart",
          "periodEnd",
          "openFindings"
        ],
        "type": "object"
      },
      "FiledReturnsListResult": {
        "properties": {
          "data": {
            "properties": {
              "returns": {
                "items": {
                  "$ref": "#/components/schemas/FiledReturnSummary"
                },
                "type": "array"
              }
            },
            "required": [
              "returns"
            ],
            "type": "object"
          },
          "success": {
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "FilingAmendmentFiscalYearQuery": {
        "properties": {
          "fiscal_year": {
            "description": "Fiscal year (YYYY)",
            "example": 2025,
            "type": "integer"
          }
        },
        "required": [
          "fiscal_year"
        ],
        "type": "object"
      },
      "FilingReceiptFacts": {
        "description": "What the file name and the receipt text say. A fact the receipt does not state is null. receiptNumber is an e-Tax 受付番号 (20 digits opening with the transmission date and time) or an eLTAX one (R1-2026-…); a placeholder is null.",
        "properties": {
          "authorities": {
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "authority": {
            "description": "提出先: the first one named",
            "example": "群馬県",
            "nullable": true,
            "type": "string"
          },
          "date": {
            "description": "受付日時, else the e-Tax 受付番号’s date, else the file name’s",
            "format": "date",
            "nullable": true,
            "type": "string"
          },
          "fiscalPeriod": {
            "nullable": true,
            "properties": {
              "from": {
                "format": "date",
                "type": "string"
              },
              "to": {
                "format": "date",
                "type": "string"
              }
            },
            "required": [
              "from",
              "to"
            ],
            "type": "object"
          },
          "procedureName": {
            "example": "法人都道府県民税・事業税・特別法人事業税予定申告",
            "nullable": true,
            "type": "string"
          },
          "procedureWords": {
            "example": [
              "予定申告"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "receiptNumber": {
            "example": "R1-2026-12345678",
            "nullable": true,
            "type": "string"
          },
          "system": {
            "enum": [
              "eltax",
              "etax"
            ],
            "nullable": true,
            "type": "string"
          },
          "taxItems": {
            "example": [
              "均等割"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          }
        },
        "required": [
          "date",
          "system",
          "procedureWords",
          "procedureName",
          "authority",
          "authorities",
          "receiptNumber",
          "taxItems",
          "fiscalPeriod"
        ],
        "type": "object"
      },
      "FilingReceiptItem": {
        "properties": {
          "fileId": {
            "description": "file_uploads id (intake) or filing_workspace_files id (etax_archive); null when not saved",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "fileName": {
            "type": "string"
          },
          "parsed": {
            "allOf": [
              {
                "$ref": "#/components/schemas/FilingReceiptFacts"
              }
            ],
            "nullable": true
          },
          "reason": {
            "description": "matched → suggestion is set. no_candidate / ambiguous → no single open deadline (0 or 2+); the file is still saved. unsupported_file / upload_failed → the file was not saved.",
            "enum": [
              "matched",
              "no_date",
              "future_date",
              "no_procedure",
              "no_candidate",
              "ambiguous",
              "unsupported_file",
              "upload_failed"
            ],
            "type": "string"
          },
          "source": {
            "enum": [
              "intake",
              "etax_archive"
            ],
            "type": "string"
          },
          "suggestion": {
            "allOf": [
              {
                "$ref": "#/components/schemas/FilingReceiptSuggestion"
              }
            ],
            "nullable": true
          }
        },
        "required": [
          "fileId",
          "fileName",
          "source",
          "parsed",
          "suggestion",
          "reason"
        ],
        "type": "object"
      },
      "FilingReceiptItems": {
        "properties": {
          "items": {
            "items": {
              "$ref": "#/components/schemas/FilingReceiptItem"
            },
            "type": "array"
          }
        },
        "required": [
          "items"
        ],
        "type": "object"
      },
      "FilingReceiptSuggestion": {
        "description": "The one open deadline the receipt closes, and the record confirming it would write.",
        "properties": {
          "deadlineId": {
            "format": "uuid",
            "type": "string"
          },
          "dueDate": {
            "format": "date",
            "type": "string"
          },
          "filedOn": {
            "format": "date",
            "type": "string"
          },
          "filingMethod": {
            "enum": [
              "eltax",
              "etax"
            ],
            "nullable": true,
            "type": "string"
          },
          "receiptNumber": {
            "nullable": true,
            "type": "string"
          },
          "title": {
            "example": "中間申告（予定申告）均等割（群馬県）",
            "type": "string"
          }
        },
        "required": [
          "deadlineId",
          "title",
          "dueDate",
          "filedOn",
          "filingMethod",
          "receiptNumber"
        ],
        "type": "object"
      },
      "FinancialReportResponse": {
        "properties": {
          "data": {
            "description": "Report data structure varies by report type",
            "type": "object"
          },
          "message": {
            "example": "Financial report generated successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "FinancialSummaryResponse": {
        "description": "Composite financial summary (TB + P&L + BS) for dock charts",
        "properties": {
          "balanceSheet": {
            "properties": {
              "isBalanced": {
                "description": "Assets = Liabilities + Equity",
                "example": true,
                "type": "boolean"
              },
              "totalAssets": {
                "description": "資産合計 (JPY)",
                "example": 15000000,
                "type": "integer"
              },
              "totalEquity": {
                "description": "純資産合計 (JPY)",
                "example": 13000000,
                "type": "integer"
              },
              "totalLiabilities": {
                "description": "負債合計 (JPY)",
                "example": 2000000,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "generatedAt": {
            "example": "2026-02-16T08:00:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "profitLoss": {
            "properties": {
              "grossProfit": {
                "description": "売上総利益 (JPY)",
                "example": 8500000,
                "type": "integer"
              },
              "netIncome": {
                "description": "当期純利益 (JPY)",
                "example": 5300000,
                "type": "integer"
              },
              "operatingIncome": {
                "description": "営業利益 (JPY)",
                "example": 5300000,
                "type": "integer"
              },
              "totalExpenses": {
                "description": "経費合計 (JPY)",
                "example": 3200000,
                "type": "integer"
              },
              "totalRevenue": {
                "description": "売上高 (JPY)",
                "example": 8500000,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "trialBalance": {
            "properties": {
              "accountCount": {
                "description": "Active accounts in period",
                "example": 12,
                "type": "integer"
              },
              "discrepancy": {
                "description": "Debit minus credit",
                "example": 0,
                "type": "integer"
              },
              "isBalanced": {
                "description": "貸借一致",
                "example": true,
                "type": "boolean"
              },
              "totalCredit": {
                "description": "JPY integer",
                "example": 12345678,
                "type": "integer"
              },
              "totalDebit": {
                "description": "JPY integer",
                "example": 12345678,
                "type": "integer"
              }
            },
            "type": "object"
          }
        },
        "type": "object"
      },
      "FindingsListResult": {
        "properties": {
          "findings": {
            "items": {
              "$ref": "#/components/schemas/CanonicalFinding"
            },
            "type": "array"
          },
          "lens": {
            "description": "表示レンズ",
            "enum": [
              "triage",
              "engine",
              "period"
            ],
            "type": "string"
          },
          "scope": {
            "description": "クエリスコープ",
            "type": "string"
          },
          "summary": {
            "properties": {
              "blocker": {
                "type": "integer"
              },
              "bySource": {
                "description": "The same counts per engine (BL-1174) — all four engines, zeros included, in a fixed order. Present with `summary=1` too. An array so the response camelizer never renames an engine.",
                "items": {
                  "properties": {
                    "blocker": {
                      "type": "integer"
                    },
                    "info": {
                      "type": "integer"
                    },
                    "sourceEngine": {
                      "enum": [
                        "pre_filing_review",
                        "integrity_check",
                        "month_end",
                        "financial_advisory"
                      ],
                      "type": "string"
                    },
                    "total": {
                      "type": "integer"
                    },
                    "warning": {
                      "type": "integer"
                    }
                  },
                  "required": [
                    "sourceEngine",
                    "total",
                    "blocker",
                    "warning",
                    "info"
                  ],
                  "type": "object"
                },
                "type": "array"
              },
              "info": {
                "type": "integer"
              },
              "total": {
                "type": "integer"
              },
              "warning": {
                "type": "integer"
              }
            },
            "required": [
              "total",
              "blocker",
              "warning",
              "info",
              "bySource"
            ],
            "type": "object"
          }
        },
        "required": [
          "lens",
          "scope",
          "findings",
          "summary"
        ],
        "type": "object"
      },
      "FiscalPeriod": {
        "properties": {
          "closed_at": {
            "description": "Period close timestamp",
            "example": "2024-07-01T09:00:00.000Z",
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "closed_by": {
            "description": "User who closed the period",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "created_at": {
            "example": "2024-04-01T00:00:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "end_date": {
            "description": "Period end date in YYYYMMDD format",
            "example": 20240630,
            "type": "integer"
          },
          "id": {
            "description": "Fiscal period unique identifier",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "is_posting_locked": {
            "description": "Whether posting is locked for this period",
            "example": false,
            "type": "boolean"
          },
          "period_name": {
            "description": "Fiscal period name",
            "example": "2024年度第1四半期",
            "type": "string"
          },
          "period_type": {
            "description": "Type of fiscal period",
            "enum": [
              "ANNUAL",
              "MONTHLY",
              "QUARTERLY"
            ],
            "example": "MONTHLY",
            "type": "string"
          },
          "reopen_reason": {
            "description": "Reason for reopening the period",
            "example": "Additional adjustments required for year-end audit",
            "nullable": true,
            "type": "string"
          },
          "reopened_at": {
            "description": "Period reopen timestamp",
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "reopened_by": {
            "description": "User who reopened the period",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "start_date": {
            "description": "Period start date in YYYYMMDD format",
            "example": 20240401,
            "type": "integer"
          },
          "status": {
            "$ref": "#/components/schemas/FiscalPeriodStatus"
          },
          "updated_at": {
            "example": "2024-04-01T00:00:00.000Z",
            "format": "date-time",
            "type": "string"
          }
        },
        "required": [
          "id",
          "period_name",
          "period_type",
          "start_date",
          "end_date",
          "status",
          "is_posting_locked",
          "created_at",
          "updated_at"
        ],
        "type": "object"
      },
      "FiscalPeriodCloseValidation": {
        "properties": {
          "blockers": {
            "description": "Issues that prevent period closure",
            "items": {
              "$ref": "#/components/schemas/ValidationIssue"
            },
            "type": "array"
          },
          "canClose": {
            "description": "Whether the period can be closed",
            "example": false,
            "type": "boolean"
          },
          "summary": {
            "properties": {
              "missingEvidenceJournals": {
                "description": "Number of journal entries missing evidence",
                "example": 1,
                "type": "integer"
              },
              "pendingExpenseReports": {
                "description": "Number of pending expense reports",
                "example": 2,
                "type": "integer"
              },
              "suspenseAccountBalance": {
                "description": "Balance in suspense accounts",
                "example": 25000,
                "format": "decimal",
                "type": "number"
              },
              "unreconciledBankTransactions": {
                "description": "Number of unreconciled bank transactions",
                "example": 3,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "warnings": {
            "description": "Issues that should be reviewed but do not prevent closure",
            "items": {
              "$ref": "#/components/schemas/ValidationIssue"
            },
            "type": "array"
          }
        },
        "required": [
          "canClose",
          "blockers",
          "warnings",
          "summary"
        ],
        "type": "object"
      },
      "FiscalPeriodListResponse": {
        "properties": {
          "additionalData": {
            "properties": {
              "currentFiscalYear": {
                "example": 2024,
                "type": "integer"
              },
              "stats": {
                "properties": {
                  "closed": {
                    "example": 4,
                    "type": "integer"
                  },
                  "open": {
                    "example": 8,
                    "type": "integer"
                  },
                  "total": {
                    "example": 12,
                    "type": "integer"
                  }
                },
                "type": "object"
              }
            },
            "type": "object"
          },
          "data": {
            "items": {
              "$ref": "#/components/schemas/FiscalPeriod"
            },
            "type": "array"
          },
          "message": {
            "example": "会計期間を取得しました",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "FiscalPeriodResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/FiscalPeriod"
          },
          "message": {
            "example": "Fiscal period retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "FiscalPeriodStatus": {
        "description": "Fiscal period status in Japanese accounting workflow",
        "enum": [
          "open",
          "closing",
          "closed",
          "audited"
        ],
        "example": "open",
        "type": "string"
      },
      "FixedAsset": {
        "properties": {
          "acquisition_cost": {
            "description": "Original acquisition cost in Japanese Yen",
            "example": 150000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "acquisition_date": {
            "description": "Asset acquisition date in YYYYMMDD format",
            "example": 20240115,
            "maximum": 99991231,
            "minimum": 19000101,
            "type": "integer"
          },
          "classification": {
            "$ref": "#/components/schemas/AssetClassification",
            "description": "Asset classification according to Japanese tax law"
          },
          "closing_book_value": {
            "description": "Book value at end of fiscal period",
            "example": 120000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "created_at": {
            "description": "Asset record creation timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "created_by": {
            "description": "User ID who created the asset record",
            "example": "789e0123-e45b-67c8-d901-234567890123",
            "format": "uuid",
            "type": "string"
          },
          "deleted_at": {
            "description": "Deletion timestamp",
            "example": "2024-12-31T23:59:59.000Z",
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "depreciation_cost": {
            "description": "Annual depreciation amount",
            "example": 30000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "depreciation_method": {
            "$ref": "#/components/schemas/DepreciationMethod",
            "description": "Depreciation calculation method"
          },
          "document_id": {
            "description": "Associated document ID (purchase order, invoice, etc.)",
            "example": "456e7890-f12a-34b5-c678-901234567890",
            "format": "uuid",
            "type": "string"
          },
          "id": {
            "description": "Fixed asset unique identifier",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "in_service_date": {
            "description": "事業供用日 (YYYYMMDD). Depreciation starts in this month; null means the acquisition date is used.",
            "example": 20240201,
            "nullable": true,
            "type": "integer"
          },
          "is_deleted": {
            "description": "Soft deletion flag",
            "example": false,
            "type": "boolean"
          },
          "location": {
            "description": "Physical location of the asset",
            "example": "本社 3階 営業部",
            "maxLength": 255,
            "type": "string"
          },
          "name": {
            "description": "Asset name or description",
            "example": "デスクトップコンピュータ Dell OptiPlex 7090",
            "maxLength": 255,
            "type": "string"
          },
          "opening_book_value": {
            "description": "Book value at beginning of fiscal period",
            "example": 150000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "quantity": {
            "description": "Number of asset units",
            "example": 1,
            "minimum": 1,
            "type": "integer"
          },
          "remarks": {
            "description": "Additional notes or remarks about the asset",
            "example": "保証期間: 2027年1月まで",
            "maxLength": 255,
            "type": "string"
          },
          "shokyaku_tenant_fixture": {
            "description": "償却資産申告の対象（テナント造作）: true / false as the owner set it; null = SBC default (a 建物 whose location names 「賃借」 is included).",
            "example": null,
            "nullable": true,
            "type": "boolean"
          },
          "unit": {
            "description": "Unit of measurement (台, 個, セット, etc.)",
            "example": "台",
            "type": "string"
          },
          "updated_at": {
            "description": "Last update timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "useful_life": {
            "description": "Useful life in years for depreciation calculation",
            "example": 4,
            "minimum": 0,
            "type": "integer"
          }
        },
        "required": [
          "id",
          "name",
          "classification",
          "acquisition_date",
          "acquisition_cost",
          "document_id",
          "quantity",
          "unit",
          "opening_book_value",
          "useful_life",
          "depreciation_method",
          "location",
          "created_by",
          "created_at",
          "updated_at"
        ],
        "type": "object"
      },
      "FixedAssetCreateResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/FixedAsset"
          },
          "message": {
            "example": "Fixed asset created successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 201,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "FixedAssetDeleteResponse": {
        "properties": {
          "data": {
            "properties": {
              "deletedAt": {
                "description": "Deletion timestamp",
                "example": "2024-12-31T23:59:59.000Z",
                "format": "date-time",
                "type": "string"
              },
              "id": {
                "description": "ID of the deleted fixed asset",
                "example": "123e4567-e89b-12d3-a456-426614174000",
                "format": "uuid",
                "type": "string"
              },
              "name": {
                "description": "Name of the deleted asset",
                "example": "デスクトップコンピュータ Dell OptiPlex 7090",
                "type": "string"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Fixed asset deleted successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "FixedAssetLinkResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/FixedAssetWithTransaction"
          },
          "message": {
            "example": "Bank transaction linked to fixed asset",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "type": "object"
      },
      "FixedAssetResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/FixedAsset"
          },
          "message": {
            "example": "Fixed asset retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "FixedAssetSourceType": {
        "description": "Source type for fixed asset creation",
        "enum": [
          "manual",
          "bank_transaction",
          "document_scan",
          "import"
        ],
        "example": "bank_transaction",
        "type": "string"
      },
      "FixedAssetUpdateResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/FixedAsset"
          },
          "message": {
            "example": "Fixed asset updated successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "FixedAssetWithTransaction": {
        "allOf": [
          {
            "$ref": "#/components/schemas/FixedAsset"
          },
          {
            "properties": {
              "bank_statement_id": {
                "description": "Linked bank transaction ID",
                "format": "uuid",
                "nullable": true,
                "type": "string"
              },
              "bank_statements": {
                "description": "Linked bank transaction details",
                "nullable": true,
                "properties": {
                  "counterparty_name": {
                    "type": "string"
                  },
                  "description": {
                    "type": "string"
                  },
                  "id": {
                    "format": "uuid",
                    "type": "string"
                  },
                  "transaction_date": {
                    "example": 20241201,
                    "type": "integer"
                  },
                  "withdrawal_amount": {
                    "type": "number"
                  }
                },
                "type": "object"
              },
              "company_id": {
                "description": "Company ID",
                "format": "uuid",
                "nullable": true,
                "type": "string"
              },
              "documents": {
                "description": "Linked document details",
                "nullable": true,
                "properties": {
                  "file_name": {
                    "type": "string"
                  },
                  "id": {
                    "format": "uuid",
                    "type": "string"
                  },
                  "public_url": {
                    "type": "string"
                  }
                },
                "type": "object"
              },
              "journal_entry_id": {
                "description": "Linked journal entry ID",
                "format": "uuid",
                "nullable": true,
                "type": "string"
              },
              "linked_at": {
                "description": "When the asset was linked to a transaction",
                "format": "date-time",
                "nullable": true,
                "type": "string"
              },
              "source_type": {
                "$ref": "#/components/schemas/FixedAssetSourceType"
              }
            },
            "type": "object"
          }
        ]
      },
      "Folder": {
        "properties": {
          "color": {
            "description": "Folder color (hex code or color name)",
            "example": "#3B82F6",
            "nullable": true,
            "type": "string"
          },
          "created_at": {
            "description": "Creation timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "deleted_at": {
            "description": "Deletion timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "description": {
            "description": "Folder description",
            "example": "Contains all financial documents and receipts",
            "maxLength": 200,
            "nullable": true,
            "type": "string"
          },
          "document_id": {
            "description": "Associated document identifier",
            "example": "abc12345-def6-7890-ghij-klmnopqrstuv",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "icon": {
            "description": "Folder icon identifier",
            "example": "folder-documents",
            "nullable": true,
            "type": "string"
          },
          "id": {
            "description": "Folder unique identifier",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "is_deleted": {
            "description": "Soft deletion flag",
            "example": false,
            "type": "boolean"
          },
          "level": {
            "description": "Folder depth level (0 for root, max 3)",
            "example": 1,
            "maximum": 3,
            "minimum": 0,
            "type": "integer"
          },
          "name": {
            "description": "Folder name",
            "example": "Financial Documents",
            "maxLength": 50,
            "minLength": 1,
            "type": "string"
          },
          "parent_id": {
            "description": "Parent folder identifier (null for root folders)",
            "example": "456e7890-f12a-34b5-c678-901234567890",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "updated_at": {
            "description": "Last update timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "user_id": {
            "description": "User identifier",
            "example": "789e0123-e45b-67c8-d901-234567890123",
            "format": "uuid",
            "type": "string"
          }
        },
        "required": [
          "id",
          "user_id",
          "name",
          "level",
          "is_deleted",
          "created_at",
          "updated_at"
        ],
        "type": "object"
      },
      "FolderCreateResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/Folder"
          },
          "message": {
            "example": "Folder created successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 201,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "FolderDeleteResponse": {
        "properties": {
          "data": {
            "properties": {
              "deletedFiles": {
                "description": "Number of associated files deleted",
                "example": 15,
                "type": "integer"
              },
              "deletedFolders": {
                "description": "Number of folders deleted (including children)",
                "example": 3,
                "type": "integer"
              },
              "folderId": {
                "description": "ID of the deleted folder",
                "example": "123e4567-e89b-12d3-a456-426614174000",
                "format": "uuid",
                "type": "string"
              },
              "totalDeleted": {
                "description": "Total items deleted",
                "example": 18,
                "type": "integer"
              }
            },
            "required": [
              "deletedFolders",
              "deletedFiles",
              "totalDeleted",
              "folderId"
            ],
            "type": "object"
          },
          "message": {
            "example": "Folder deleted successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "FolderListResponse": {
        "properties": {
          "data": {
            "items": {
              "$ref": "#/components/schemas/Folder"
            },
            "type": "array"
          },
          "message": {
            "example": "Folders retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "FolderNode": {
        "properties": {
          "children": {
            "description": "Child folders (recursive structure)",
            "items": {
              "$ref": "#/components/schemas/FolderNode"
            },
            "type": "array"
          },
          "color": {
            "description": "Folder color",
            "example": "#3B82F6",
            "nullable": true,
            "type": "string"
          },
          "created_at": {
            "description": "Creation timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "document_id": {
            "description": "Associated document identifier",
            "example": "abc12345-def6-7890-ghij-klmnopqrstuv",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "icon": {
            "description": "Folder icon identifier",
            "example": "folder-documents",
            "nullable": true,
            "type": "string"
          },
          "id": {
            "description": "Folder unique identifier",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "level": {
            "description": "Folder depth level",
            "example": 1,
            "type": "integer"
          },
          "name": {
            "description": "Folder name",
            "example": "Financial Documents",
            "type": "string"
          },
          "parent_id": {
            "description": "Parent folder identifier",
            "example": "456e7890-f12a-34b5-c678-901234567890",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "updated_at": {
            "description": "Last update timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          }
        },
        "required": [
          "id",
          "name",
          "level",
          "created_at",
          "updated_at",
          "children"
        ],
        "type": "object"
      },
      "FolderResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/Folder"
          },
          "message": {
            "example": "Folder retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "FolderTreeResponse": {
        "properties": {
          "data": {
            "description": "Hierarchical folder tree structure",
            "items": {
              "$ref": "#/components/schemas/FolderNode"
            },
            "type": "array"
          },
          "message": {
            "example": "User folders tree retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "FullValidationResponse": {
        "properties": {
          "generatedAt": {
            "format": "date-time",
            "type": "string"
          },
          "health": {
            "$ref": "#/components/schemas/AccountingHealthResponse"
          },
          "problems": {
            "items": {
              "$ref": "#/components/schemas/ProblematicTransaction"
            },
            "type": "array"
          }
        },
        "required": [
          "health",
          "problems",
          "generatedAt"
        ],
        "type": "object"
      },
      "FundingNeeds": {
        "description": "Funding requirements for the business",
        "enum": [
          "none",
          "loan",
          "vc",
          "undecided"
        ],
        "example": "loan",
        "type": "string"
      },
      "GamificationProgress": {
        "properties": {
          "achievements": {
            "items": {
              "$ref": "#/components/schemas/UserAchievement"
            },
            "type": "array"
          },
          "active_goals_count": {
            "example": 3,
            "type": "integer"
          },
          "company_id": {
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "completed_goals_count": {
            "example": 8,
            "type": "integer"
          },
          "created_at": {
            "format": "date-time",
            "type": "string"
          },
          "current_level": {
            "example": 5,
            "type": "integer"
          },
          "current_login_streak": {
            "example": 7,
            "type": "integer"
          },
          "current_xp": {
            "example": 750,
            "type": "integer"
          },
          "daily_xp_events": {
            "example": {
              "document_create": 5,
              "login": 1
            },
            "type": "object"
          },
          "earned_achievements_count": {
            "example": 12,
            "type": "integer"
          },
          "goals": {
            "items": {
              "$ref": "#/components/schemas/UserGoal"
            },
            "type": "array"
          },
          "last_login_date": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "last_updated_at": {
            "format": "date-time",
            "type": "string"
          },
          "level_info": {
            "$ref": "#/components/schemas/LevelInfoResponse"
          },
          "level_name": {
            "properties": {
              "en": {
                "example": "Junior Accountant",
                "type": "string"
              },
              "ja": {
                "example": "経理担当",
                "type": "string"
              }
            },
            "type": "object"
          },
          "level_tier": {
            "example": "beginner",
            "type": "string"
          },
          "longest_login_streak": {
            "example": 30,
            "type": "integer"
          },
          "next_level_info": {
            "description": "Next level info, null at max level",
            "oneOf": [
              {
                "$ref": "#/components/schemas/NextLevelInfoResponse"
              },
              {
                "type": "null"
              }
            ]
          },
          "recent_achievements": {
            "items": {
              "$ref": "#/components/schemas/RecentAchievement"
            },
            "type": "array"
          },
          "streak_multiplier": {
            "description": "Current streak multiplier based on login streak",
            "example": 1.1,
            "type": "number"
          },
          "total_achievements_count": {
            "example": 50,
            "type": "integer"
          },
          "total_documents_processed": {
            "example": 45,
            "type": "integer"
          },
          "total_time_saved_minutes": {
            "example": 120,
            "type": "integer"
          },
          "total_transactions_reconciled": {
            "example": 200,
            "type": "integer"
          },
          "total_xp_earned": {
            "example": 750,
            "type": "integer"
          },
          "user_id": {
            "format": "uuid",
            "type": "string"
          },
          "xp_progress_percent": {
            "example": 75,
            "type": "integer"
          },
          "xp_to_next_level": {
            "example": 250,
            "type": "integer"
          }
        },
        "type": "object"
      },
      "GeneralLedgerLine": {
        "properties": {
          "account_id": {
            "description": "Account identifier for this ledger line",
            "example": "456e7890-f12a-34b5-c678-901234567890",
            "format": "uuid",
            "type": "string"
          },
          "created_at": {
            "description": "Creation timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "credit_amount": {
            "description": "Credit amount for this ledger line (貸方金額)",
            "example": 0,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "debit_amount": {
            "description": "Debit amount for this ledger line (借方金額)",
            "example": 100000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "description": {
            "description": "Transaction description",
            "example": "売上計上 - 株式会社ABC",
            "nullable": true,
            "type": "string"
          },
          "entry_date": {
            "description": "Entry date in YYYYMMDD format",
            "example": 20240115,
            "maximum": 99991231,
            "minimum": 19000101,
            "type": "integer"
          },
          "id": {
            "description": "General ledger line unique identifier",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "journal_entry_id": {
            "description": "Source journal entry identifier",
            "example": "789e0123-e45b-67c8-d901-234567890123",
            "format": "uuid",
            "type": "string"
          },
          "running_balance": {
            "description": "Running balance after this transaction (残高)",
            "example": 250000,
            "format": "decimal",
            "type": "number"
          },
          "user_id": {
            "description": "User who posted this ledger entry",
            "example": "abc12345-def6-7890-ghij-klmnopqrstuv",
            "format": "uuid",
            "type": "string"
          }
        },
        "required": [
          "id",
          "account_id",
          "journal_entry_id",
          "debit_amount",
          "credit_amount",
          "running_balance",
          "entry_date",
          "user_id",
          "created_at"
        ],
        "type": "object"
      },
      "GeneralTaxationCalculation": {
        "properties": {
          "inputTax": {
            "description": "Total input tax (仮払消費税合計)",
            "example": 330000,
            "format": "decimal",
            "type": "number"
          },
          "outputTax": {
            "description": "Total output tax (仮受消費税合計)",
            "example": 550000,
            "format": "decimal",
            "type": "number"
          },
          "taxDue": {
            "description": "Tax due amount (納付税額)",
            "example": 220000,
            "format": "decimal",
            "type": "number"
          }
        },
        "required": [
          "outputTax",
          "inputTax",
          "taxDue"
        ],
        "type": "object"
      },
      "GenerateDocumentRequest": {
        "properties": {
          "description": {
            "description": "Natural language description of the document content to generate. The AI will use this along with company info and document-specific templates to generate structured JSON content.",
            "example": "12月分の給与明細を作成。基本給30万円、残業手当5万円、交通費2万円。社会保険料と所得税を控除。",
            "minLength": 1,
            "type": "string"
          },
          "type": {
            "description": "Document type for AI generation. Only document types with templates are supported. Tax documents are generated from accounting data, not AI.",
            "enum": [
              "sales_quotation",
              "purchase_order",
              "delivery_note",
              "sales_invoice",
              "service_agreement",
              "travel",
              "claims",
              "fixed_asset",
              "payment",
              "salary_slip",
              "company_info",
              "company_decision",
              "company_representative",
              "company_capital",
              "company_office_location",
              "rules_claims"
            ],
            "example": "salary_slip",
            "type": "string"
          }
        },
        "required": [
          "description",
          "type"
        ],
        "type": "object"
      },
      "GenerateJournalEntryApiResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/GenerateJournalEntryResponse"
          },
          "message": {
            "example": "Journal entry generated successfully",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "GenerateJournalEntryRequest": {
        "properties": {
          "journalType": {
            "$ref": "#/components/schemas/JournalType"
          },
          "matchedDocument": {
            "$ref": "#/components/schemas/MatchedDocument"
          },
          "transaction": {
            "$ref": "#/components/schemas/TransactionWithBankAccount"
          }
        },
        "required": [
          "transaction",
          "journalType"
        ],
        "type": "object"
      },
      "GenerateJournalEntryResponse": {
        "properties": {
          "appliedPreferences": {
            "description": "User preferences that were applied",
            "items": {
              "properties": {
                "description": {
                  "example": "AWS関連は通信費として処理",
                  "type": "string"
                },
                "preferenceId": {
                  "example": "pref_123",
                  "type": "string"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "confidence": {
            "description": "AI confidence score for the journal entry (0.0-1.0)",
            "example": 0.92,
            "format": "double",
            "maximum": 1,
            "minimum": 0,
            "type": "number"
          },
          "correctedEntries": {
            "description": "Auto-corrected entries if validation failed but correction was possible (v4.29)",
            "items": {
              "$ref": "#/components/schemas/JournalEntryLine"
            },
            "type": "array"
          },
          "explanation": {
            "description": "Explanation of journal entry logic",
            "example": "出張費精算書に基づき、交通費と宿泊費を適切な勘定科目に仕訳しました",
            "type": "string"
          },
          "interestCalculation": {
            "$ref": "#/components/schemas/InterestIncomeCalculation",
            "description": "v4.30: Interest income calculation (only present for bank interest transactions). Contains net/gross/withholding amounts and account codes for the 3-line journal entry."
          },
          "journalEntry": {
            "$ref": "#/components/schemas/JournalEntry"
          },
          "suggestedJournalType": {
            "description": "AI-suggested journal type",
            "example": "expense",
            "type": "string"
          },
          "transactionAnalysis": {
            "$ref": "#/components/schemas/TransactionAnalysis"
          },
          "validation": {
            "$ref": "#/components/schemas/JournalEntryValidation"
          },
          "warnings": {
            "description": "Warnings or considerations (includes validation errors)",
            "example": [
              "消費税区分の確認が必要です",
              "領収書の保管を確認してください"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          }
        },
        "required": [
          "journalEntry",
          "explanation",
          "warnings"
        ],
        "type": "object"
      },
      "GenerateJournalEntrySimpleRequest": {
        "description": "Simplified request format for journal entry generation (v4.23). Frontend-friendly.",
        "properties": {
          "amount": {
            "description": "Transaction amount - negative for withdrawals (required if transactionId not provided)",
            "example": -12345,
            "type": "number"
          },
          "bankAccountCode": {
            "default": "1100",
            "description": "Bank account code (defaults to 1100 普通預金)",
            "example": "1100",
            "type": "string"
          },
          "bankAccountName": {
            "default": "普通預金",
            "description": "Bank account name",
            "example": "普通預金",
            "type": "string"
          },
          "context": {
            "$ref": "#/components/schemas/CompanyContext"
          },
          "date": {
            "description": "Transaction date (required if transactionId not provided)",
            "example": "2026-01-15",
            "format": "date",
            "type": "string"
          },
          "description": {
            "description": "Transaction description (required if transactionId not provided)",
            "example": "AWS利用料金",
            "type": "string"
          },
          "journalType": {
            "default": "auto",
            "description": "Journal type - use \"auto\" for AI to determine best type",
            "enum": [
              "reimbursement",
              "income",
              "expense",
              "transfer",
              "suspense",
              "auto"
            ],
            "example": "expense",
            "type": "string"
          },
          "notes": {
            "description": "Additional instructions for AI",
            "example": "源泉徴収がある場合は考慮してください",
            "type": "string"
          },
          "suggestedAccountCode": {
            "description": "Account code from previous categorization (helps AI)",
            "example": "5120",
            "type": "string"
          },
          "suggestedAccountName": {
            "description": "Account name from previous categorization",
            "example": "通信費",
            "type": "string"
          },
          "taxCategory": {
            "description": "Tax category from previous categorization",
            "example": "課税仕入",
            "type": "string"
          },
          "transactionId": {
            "description": "Transaction ID to fetch from database. Either this OR inline fields required.",
            "example": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
            "format": "uuid",
            "type": "string"
          },
          "transactionType": {
            "description": "Transaction type (auto-detected from amount if not provided)",
            "enum": [
              "deposit",
              "withdrawal"
            ],
            "example": "withdrawal",
            "type": "string"
          }
        },
        "type": "object"
      },
      "GenerateJournalEntrySimpleResponse": {
        "allOf": [
          {
            "$ref": "#/components/schemas/GenerateJournalEntryResponse"
          },
          {
            "properties": {
              "alternatives": {
                "description": "2 alternative journal entry suggestions for users to choose from (v4.29)",
                "example": [
                  {
                    "confidence": 0.75,
                    "explanation": "売掛金の回収として計上（既に売上計上済みの場合）",
                    "journalEntry": {
                      "date": "2026-01-15",
                      "description": "振込 サンプルシヨウジ（カ",
                      "entries": [
                        {
                          "accountCode": "1100",
                          "accountName": "普通預金",
                          "amount": 550000,
                          "side": "debit"
                        },
                        {
                          "accountCode": "1130",
                          "accountName": "売掛金",
                          "amount": 550000,
                          "side": "credit"
                        }
                      ]
                    },
                    "suggestedJournalType": "income"
                  },
                  {
                    "confidence": 0.45,
                    "explanation": "前受金として計上（まだ役務提供前の場合）",
                    "journalEntry": {
                      "date": "2026-01-15",
                      "description": "振込 サンプルシヨウジ（カ",
                      "entries": [
                        {
                          "accountCode": "1100",
                          "accountName": "普通預金",
                          "amount": 550000,
                          "side": "debit"
                        },
                        {
                          "accountCode": "2400",
                          "accountName": "前受金",
                          "amount": 550000,
                          "side": "credit"
                        }
                      ]
                    },
                    "suggestedJournalType": "income"
                  }
                ],
                "items": {
                  "properties": {
                    "confidence": {
                      "description": "Confidence score for this alternative",
                      "example": 0.75,
                      "format": "double",
                      "maximum": 1,
                      "minimum": 0,
                      "type": "number"
                    },
                    "explanation": {
                      "description": "Japanese explanation for why this alternative might be correct",
                      "example": "売掛金の回収として計上（既に売上計上済みの場合）",
                      "type": "string"
                    },
                    "journalEntry": {
                      "$ref": "#/components/schemas/JournalEntry"
                    },
                    "suggestedJournalType": {
                      "description": "Suggested journal type for this alternative",
                      "example": "income",
                      "type": "string"
                    },
                    "validation": {
                      "$ref": "#/components/schemas/JournalEntryValidation"
                    }
                  },
                  "type": "object"
                },
                "type": "array"
              },
              "appliedPreferences": {
                "description": "User preferences that were applied",
                "items": {
                  "properties": {
                    "description": {
                      "type": "string"
                    },
                    "preferenceId": {
                      "type": "string"
                    }
                  },
                  "type": "object"
                },
                "type": "array"
              },
              "confidence": {
                "description": "AI confidence in the journal entry",
                "example": 0.92,
                "format": "double",
                "maximum": 1,
                "minimum": 0,
                "type": "number"
              },
              "decisionSource": {
                "description": "Who produced the answer: rule (deterministic, no AI), history (the tenant own decisive booking history, no AI), jev (Jev decision model, BE ADR-0013), llm (the chat model of the user)",
                "enum": [
                  "rule",
                  "history",
                  "jev",
                  "llm"
                ],
                "example": "history",
                "type": "string"
              },
              "suggestedJournalType": {
                "description": "AI-suggested journal type (when auto was used)",
                "example": "expense",
                "type": "string"
              }
            },
            "type": "object"
          }
        ]
      },
      "GenerateQualifiedInvoiceRequest": {
        "properties": {
          "bank_info": {
            "$ref": "#/components/schemas/BankInfo"
          },
          "due_date": {
            "description": "Payment due date in YYYYMMDD format (支払期限)",
            "example": 20240415,
            "type": "integer"
          },
          "items": {
            "description": "Invoice items (請求項目)",
            "example": [
              {
                "amount": 500000,
                "description": "Webサイト制作業務",
                "quantity": 1,
                "tax_rate_category": "standard_10",
                "unit": "式",
                "unit_price": 500000
              }
            ],
            "items": {
              "$ref": "#/components/schemas/QualifiedInvoiceItem"
            },
            "minItems": 1,
            "type": "array"
          },
          "notes": {
            "description": "Additional notes (備考)",
            "example": [
              "納期: 2024年4月末",
              "お支払いは請求書発行日より30日以内にお願いします"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "recipient_address": {
            "description": "Recipient address (受領事業者住所)",
            "example": "東京都渋谷区1-1-1",
            "type": "string"
          },
          "recipient_name": {
            "description": "Recipient name (受領事業者名)",
            "example": "株式会社クライアント",
            "minLength": 1,
            "type": "string"
          },
          "recipient_registration_number": {
            "description": "Recipient registration number for verification (T + 13 digits)",
            "example": "T1234567890123",
            "pattern": "^T\\d{13}$",
            "type": "string"
          },
          "save_to_database": {
            "default": true,
            "description": "Whether to save invoice to database",
            "example": true,
            "type": "boolean"
          },
          "transaction_date": {
            "description": "Transaction date in YYYYMMDD format (取引年月日)",
            "example": 20240315,
            "type": "integer"
          }
        },
        "required": [
          "recipient_name",
          "transaction_date",
          "items"
        ],
        "type": "object"
      },
      "GenerateRecoveryCodesRequest": {
        "properties": {
          "confirm_regenerate": {
            "default": false,
            "description": "Must be true if codes already exist",
            "type": "boolean"
          }
        },
        "type": "object"
      },
      "GeneratedRecoveryCodesResponse": {
        "properties": {
          "data": {
            "properties": {
              "codes": {
                "description": "IMPORTANT: Codes are shown ONLY ONCE",
                "example": [
                  "ABCD-1234-EFGH",
                  "IJKL-5678-MNOP",
                  "QRST-9012-UVWX",
                  "YZAB-3456-CDEF",
                  "GHIJ-7890-KLMN",
                  "OPQR-1357-STUV",
                  "WXYZ-2468-ABCD",
                  "EFGH-9135-IJKL"
                ],
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              "generatedAt": {
                "format": "date-time",
                "type": "string"
              },
              "totalCodes": {
                "example": 8,
                "type": "integer"
              },
              "usedCodes": {
                "example": 0,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "リカバリーコードを生成しました",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "type": "object"
      },
      "GenericLinkedDocument": {
        "description": "Linked document response (camelCase - auto-converted from snake_case)",
        "properties": {
          "allocatedAmount": {
            "description": "Amount allocated from this document",
            "type": "number"
          },
          "amount": {
            "description": "Document amount (extracted from content)",
            "type": "number"
          },
          "documentType": {
            "description": "Document type (e.g., receipt, invoice)",
            "type": "string"
          },
          "id": {
            "description": "Document ID",
            "format": "uuid",
            "type": "string"
          },
          "issueDate": {
            "description": "Issue date in YYYYMMDD format",
            "type": "integer"
          },
          "linkId": {
            "description": "Link record ID",
            "format": "uuid",
            "type": "string"
          },
          "linkedAt": {
            "description": "When the document was linked",
            "format": "date-time",
            "type": "string"
          },
          "linkedBy": {
            "description": "User who created the link",
            "format": "uuid",
            "type": "string"
          },
          "name": {
            "description": "Document name",
            "type": "string"
          },
          "note": {
            "description": "Link note",
            "type": "string"
          },
          "relationshipType": {
            "description": "Type of relationship",
            "type": "string"
          },
          "vendorName": {
            "description": "Vendor name (extracted from content)",
            "type": "string"
          }
        },
        "type": "object"
      },
      "GetAnalysisResponse": {
        "description": "Response for GET /api/ai-reconciliation/analysis/:transactionId",
        "properties": {
          "data": {
            "properties": {
              "analysis": {
                "$ref": "#/components/schemas/CachedAnalysisResult",
                "nullable": true
              },
              "cacheInfo": {
                "properties": {
                  "expiresAt": {
                    "description": "When cache expires",
                    "format": "date-time",
                    "nullable": true,
                    "type": "string"
                  },
                  "fromCache": {
                    "description": "Whether result came from cache",
                    "example": true,
                    "type": "boolean"
                  },
                  "ttlSeconds": {
                    "description": "Time to live in seconds",
                    "example": 86400,
                    "nullable": true,
                    "type": "integer"
                  }
                },
                "type": "object"
              },
              "found": {
                "description": "Whether a cached analysis was found",
                "example": true,
                "type": "boolean"
              },
              "history": {
                "description": "Full history (if include_history=true)",
                "items": {
                  "$ref": "#/components/schemas/CachedAnalysisResult"
                },
                "type": "array"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Analysis retrieved from cache",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "type": "object"
      },
      "GetExchangeRatesForCurrenciesRequest": {
        "properties": {
          "currencies": {
            "description": "Array of currency codes to retrieve rates for",
            "example": [
              "USD",
              "EUR",
              "GBP"
            ],
            "items": {
              "maxLength": 3,
              "minLength": 3,
              "type": "string"
            },
            "maxItems": 10,
            "minItems": 1,
            "type": "array"
          },
          "end_date": {
            "description": "End date in YYYYMMDD format",
            "example": 20240131,
            "maximum": 20991231,
            "minimum": 20000101,
            "type": "integer"
          },
          "start_date": {
            "description": "Start date in YYYYMMDD format",
            "example": 20240101,
            "maximum": 20991231,
            "minimum": 20000101,
            "type": "integer"
          }
        },
        "required": [
          "start_date",
          "end_date",
          "currencies"
        ],
        "type": "object"
      },
      "GetLinksResponse": {
        "properties": {
          "items": {
            "description": "Same as links (backwards compatibility)",
            "items": {
              "$ref": "#/components/schemas/LinkWithDocument"
            },
            "type": "array"
          },
          "limit": {
            "type": "integer"
          },
          "links": {
            "description": "Array of links with enriched documents",
            "items": {
              "$ref": "#/components/schemas/LinkWithDocument"
            },
            "type": "array"
          },
          "offset": {
            "type": "integer"
          },
          "total": {
            "type": "integer"
          }
        },
        "type": "object"
      },
      "GetMessagesRequest": {
        "properties": {
          "limit": {
            "default": 20,
            "description": "Number of messages per page",
            "example": 20,
            "maximum": 100,
            "type": "integer"
          },
          "page": {
            "default": 1,
            "description": "Page number for pagination",
            "example": 1,
            "minimum": 1,
            "type": "integer"
          },
          "status": {
            "default": "all",
            "description": "Filter messages by read status",
            "enum": [
              "all",
              "unread",
              "read"
            ],
            "example": "all",
            "type": "string"
          }
        },
        "type": "object"
      },
      "GetMunicipalitiesRequest": {
        "properties": {
          "language": {
            "default": "ja",
            "description": "Response language",
            "enum": [
              "ja",
              "en"
            ],
            "example": "ja",
            "type": "string"
          },
          "prefecture": {
            "description": "Prefecture name in Japanese",
            "example": "東京都",
            "type": "string"
          }
        },
        "required": [
          "prefecture"
        ],
        "type": "object"
      },
      "GetTransactionsRequest": {
        "properties": {
          "area": {
            "description": "Area code or name",
            "example": "13101",
            "type": "string"
          },
          "city": {
            "description": "City name",
            "example": "千代田区",
            "type": "string"
          },
          "language": {
            "default": "ja",
            "description": "Response language",
            "enum": [
              "ja",
              "en"
            ],
            "example": "ja",
            "type": "string"
          },
          "price_classification": {
            "description": "Price classification code",
            "enum": [
              "01",
              "02"
            ],
            "example": "01",
            "type": "string"
          },
          "quarter": {
            "default": 1,
            "description": "Quarter of the year",
            "enum": [
              1,
              2,
              3,
              4
            ],
            "example": 1,
            "type": "integer"
          },
          "station": {
            "description": "Nearest station name",
            "example": "東京駅",
            "type": "string"
          },
          "year": {
            "description": "Transaction year",
            "example": 2024,
            "minimum": 2005,
            "type": "integer"
          }
        },
        "required": [
          "year",
          "area",
          "city",
          "station"
        ],
        "type": "object"
      },
      "GitCommit": {
        "properties": {
          "author": {
            "description": "Commit author name",
            "example": "John Doe",
            "type": "string"
          },
          "body": {
            "description": "Commit body text",
            "nullable": true,
            "type": "string"
          },
          "date": {
            "description": "Commit date in ISO format",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "hash": {
            "description": "Full commit hash",
            "example": "a1b2c3d4e5f6789012345678901234567890abcd",
            "type": "string"
          },
          "isBreaking": {
            "description": "Whether commit contains breaking changes",
            "example": false,
            "type": "boolean"
          },
          "message": {
            "description": "Full commit message",
            "example": "feat(auth): add OAuth2 integration",
            "type": "string"
          },
          "scope": {
            "description": "Commit scope",
            "example": "auth",
            "nullable": true,
            "type": "string"
          },
          "shortHash": {
            "description": "Short commit hash",
            "example": "a1b2c3d",
            "type": "string"
          },
          "subject": {
            "description": "Commit subject line",
            "example": "add OAuth2 integration",
            "type": "string"
          },
          "type": {
            "description": "Commit type from conventional commits",
            "example": "feat",
            "type": "string"
          }
        },
        "required": [
          "hash",
          "shortHash",
          "date",
          "author",
          "message",
          "type",
          "subject",
          "isBreaking"
        ],
        "type": "object"
      },
      "GitTag": {
        "properties": {
          "date": {
            "description": "Tag creation date",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "hash": {
            "description": "Commit hash for tag",
            "example": "a1b2c3d",
            "type": "string"
          },
          "tag": {
            "description": "Git tag name",
            "example": "v1.2.3",
            "type": "string"
          }
        },
        "required": [
          "tag",
          "date",
          "hash"
        ],
        "type": "object"
      },
      "GoalDefinition": {
        "properties": {
          "description": {
            "properties": {
              "en": {
                "example": "Enter your company basic information",
                "type": "string"
              },
              "ja": {
                "example": "会社の基本情報を入力しましょう",
                "type": "string"
              }
            },
            "type": "object"
          },
          "estimatedMinutes": {
            "example": 5,
            "nullable": true,
            "type": "integer"
          },
          "id": {
            "example": "setup_company",
            "type": "string"
          },
          "isRecurring": {
            "type": "boolean"
          },
          "name": {
            "properties": {
              "en": {
                "example": "Set up company info",
                "type": "string"
              },
              "ja": {
                "example": "会社情報を設定",
                "type": "string"
              }
            },
            "type": "object"
          },
          "navigationPath": {
            "example": "/settings?tab=company-info",
            "nullable": true,
            "type": "string"
          },
          "prerequisites": {
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "type": {
            "example": "onboarding",
            "type": "string"
          },
          "xp": {
            "example": 100,
            "type": "integer"
          }
        },
        "type": "object"
      },
      "GoalOperationResponse": {
        "properties": {
          "achievements_unlocked": {
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "goal_id": {
            "type": "string"
          },
          "status": {
            "enum": [
              "locked",
              "available",
              "in_progress",
              "completed"
            ],
            "type": "string"
          },
          "xp_awarded": {
            "nullable": true,
            "type": "integer"
          }
        },
        "type": "object"
      },
      "GoogleCalendarStatus": {
        "additionalProperties": false,
        "properties": {
          "calendarName": {
            "type": "string"
          },
          "categories": {
            "items": {
              "additionalProperties": false,
              "properties": {
                "enabled": {
                  "type": "boolean"
                },
                "key": {
                  "type": "string"
                },
                "label": {
                  "type": "string"
                }
              },
              "required": [
                "key",
                "label",
                "enabled"
              ],
              "type": "object"
            },
            "type": "array"
          },
          "configured": {
            "description": "false until the owner sets GOOGLE_CALENDAR_CLIENT_ID / _SECRET (the feature is dark)",
            "type": "boolean"
          },
          "eventCount": {
            "type": "integer"
          },
          "googleEmail": {
            "nullable": true,
            "type": "string"
          },
          "lastError": {
            "nullable": true,
            "type": "string"
          },
          "lastSyncAt": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "popupReminder": {
            "description": "One popup the day before at 09:00 JST",
            "type": "boolean"
          },
          "prepEvents": {
            "description": "準備開始 events for 法人税 / 消費税 (21 days before)",
            "type": "boolean"
          },
          "pushActive": {
            "description": "A live push channel (else the nightly pull picks up edits)",
            "type": "boolean"
          },
          "removedDeadlineIds": {
            "description": "Deadlines whose event the owner deleted in Google; SBC does not re-create them",
            "items": {
              "format": "uuid",
              "type": "string"
            },
            "type": "array"
          },
          "status": {
            "enum": [
              "not_connected",
              "pending",
              "active",
              "revoked",
              "calendar_deleted",
              "disconnected"
            ],
            "type": "string"
          },
          "targetDates": {
            "description": "予定日 set by moving a due event in Google (the legal due date is unchanged)",
            "items": {
              "additionalProperties": false,
              "properties": {
                "date": {
                  "format": "date",
                  "type": "string"
                },
                "deadlineId": {
                  "format": "uuid",
                  "type": "string"
                }
              },
              "required": [
                "deadlineId",
                "date"
              ],
              "type": "object"
            },
            "type": "array"
          }
        },
        "required": [
          "configured",
          "status",
          "googleEmail",
          "calendarName",
          "lastSyncAt",
          "lastError",
          "categories",
          "prepEvents",
          "popupReminder",
          "eventCount",
          "pushActive",
          "removedDeadlineIds",
          "targetDates"
        ],
        "type": "object"
      },
      "GoogleDriveStatus": {
        "additionalProperties": false,
        "properties": {
          "archiveRootFolderId": {
            "description": "Approved files are filed under this folder",
            "nullable": true,
            "type": "string"
          },
          "archiveRootFolderName": {
            "nullable": true,
            "type": "string"
          },
          "configured": {
            "description": "false until the owner sets GOOGLE_DRIVE_CLIENT_ID / _SECRET (the feature is dark)",
            "type": "boolean"
          },
          "counts": {
            "additionalProperties": false,
            "description": "Inbox items per status",
            "properties": {
              "analyzed": {
                "type": "integer"
              },
              "applied": {
                "type": "integer"
              },
              "approved": {
                "type": "integer"
              },
              "failed": {
                "type": "integer"
              },
              "new": {
                "type": "integer"
              },
              "rejected": {
                "type": "integer"
              }
            },
            "required": [
              "new",
              "analyzed",
              "approved",
              "applied",
              "rejected",
              "failed"
            ],
            "type": "object"
          },
          "googleEmail": {
            "nullable": true,
            "type": "string"
          },
          "inboxFolderId": {
            "description": "The one folder SBC reads",
            "nullable": true,
            "type": "string"
          },
          "inboxFolderName": {
            "nullable": true,
            "type": "string"
          },
          "lastError": {
            "nullable": true,
            "type": "string"
          },
          "lastScanAt": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "status": {
            "enum": [
              "not_connected",
              "active",
              "revoked",
              "disconnected"
            ],
            "type": "string"
          }
        },
        "required": [
          "configured",
          "status",
          "googleEmail",
          "inboxFolderId",
          "inboxFolderName",
          "archiveRootFolderId",
          "archiveRootFolderName",
          "lastScanAt",
          "lastError",
          "counts"
        ],
        "type": "object"
      },
      "GoogleLoginInitiationResponse": {
        "properties": {
          "data": {
            "description": "Google OAuth authorization URL for user redirection",
            "example": "https://accounts.google.com/oauth/authorize?client_id=...&redirect_uri=...&response_type=code&scope=openid+email+profile",
            "format": "uri",
            "type": "string"
          },
          "message": {
            "example": "Google login URL generated successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "GroupedAccountsResponse": {
        "properties": {
          "data": {
            "properties": {
              "asset": {
                "description": "Asset accounts",
                "items": {
                  "$ref": "#/components/schemas/Account"
                },
                "type": "array"
              },
              "equity": {
                "description": "Equity accounts",
                "items": {
                  "$ref": "#/components/schemas/Account"
                },
                "type": "array"
              },
              "expense": {
                "description": "Expense accounts",
                "items": {
                  "$ref": "#/components/schemas/Account"
                },
                "type": "array"
              },
              "liability": {
                "description": "Liability accounts",
                "items": {
                  "$ref": "#/components/schemas/Account"
                },
                "type": "array"
              },
              "revenue": {
                "description": "Revenue accounts",
                "items": {
                  "$ref": "#/components/schemas/Account"
                },
                "type": "array"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Accounts retrieved successfully",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "GroupedModelsResponse": {
        "properties": {
          "data": {
            "items": {
              "$ref": "#/components/schemas/ProviderWithModels"
            },
            "type": "array"
          },
          "message": {
            "example": "Grouped models retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "GroupingSuggestionsResponse": {
        "properties": {
          "data": {
            "properties": {
              "session_id": {
                "format": "uuid",
                "type": "string"
              },
              "suggestions": {
                "items": {
                  "properties": {
                    "file_count": {
                      "example": 3,
                      "type": "integer"
                    },
                    "file_ids": {
                      "description": "file_uploads UUIDs — can be passed to addFilesToGroup directly",
                      "items": {
                        "format": "uuid",
                        "type": "string"
                      },
                      "type": "array"
                    },
                    "files": {
                      "items": {
                        "properties": {
                          "file_name": {
                            "type": "string"
                          },
                          "file_type": {
                            "type": "string"
                          },
                          "id": {
                            "format": "uuid",
                            "type": "string"
                          }
                        },
                        "type": "object"
                      },
                      "type": "array"
                    },
                    "group_type": {
                      "example": "ai_suggested",
                      "type": "string"
                    },
                    "label": {
                      "example": "receipt",
                      "type": "string"
                    },
                    "reason": {
                      "example": "3 receipt file(s) detected",
                      "type": "string"
                    },
                    "target_document_type": {
                      "example": "claims",
                      "nullable": true,
                      "type": "string"
                    },
                    "total_amount": {
                      "example": 5500,
                      "type": "integer"
                    }
                  },
                  "type": "object"
                },
                "type": "array"
              },
              "total_files": {
                "example": 5,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "message": {
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "type": "object"
      },
      "GuidanceFact": {
        "properties": {
          "href": {
            "description": "The page that states this value (a 均等割 税率表, the eLTAX tool), when it has one.",
            "example": "https://www.pref.gunma.jp/site/tax/5383.html",
            "format": "uri",
            "type": "string"
          },
          "key": {
            "example": "evidence",
            "type": "string"
          },
          "label": {
            "example": "加入の根拠",
            "type": "string"
          },
          "value": {
            "example": "社会保険料の通知・給与明細（役員報酬・給与）",
            "type": "string"
          }
        },
        "required": [
          "key",
          "label",
          "value"
        ],
        "type": "object"
      },
      "GuidancePayment": {
        "properties": {
          "bookings": {
            "description": "One proposed 仕訳 per paid withdrawal (paid or partial) that has none yet: one debit per account (事業税・特別法人事業税 → 524 租税公課; 法人税割・均等割・法人税・地方法人税 → 701 法人税等) and 1100 普通預金 on the credit side. Posted only by the owner, through POST /reconciliation/create-compound-journal.",
            "items": {
              "properties": {
                "bankTransactionId": {
                  "format": "uuid",
                  "type": "string"
                },
                "description": {
                  "example": "中間納付 東京都（渋谷都税事務所） ― PE 地方税共同機構 26287001044",
                  "type": "string"
                },
                "entries": {
                  "items": {
                    "properties": {
                      "accountCode": {
                        "example": "524",
                        "type": "string"
                      },
                      "accountName": {
                        "example": "租税公課",
                        "type": "string"
                      },
                      "creditAmount": {
                        "example": 0,
                        "type": "integer"
                      },
                      "debitAmount": {
                        "example": 367300,
                        "type": "integer"
                      },
                      "description": {
                        "type": "string"
                      },
                      "taxCategory": {
                        "example": "対象外",
                        "nullable": true,
                        "type": "string"
                      }
                    },
                    "required": [
                      "accountCode",
                      "accountName",
                      "debitAmount",
                      "creditAmount",
                      "description",
                      "taxCategory"
                    ],
                    "type": "object"
                  },
                  "type": "array"
                }
              },
              "required": [
                "bankTransactionId",
                "description",
                "entries"
              ],
              "type": "object"
            },
            "type": "array"
          },
          "channel": {
            "description": "How this company paid this payee last time (the bank's Pay-easy line).",
            "nullable": true,
            "properties": {
              "bankLabel": {
                "example": "PE 地方税共同機構",
                "type": "string"
              },
              "kind": {
                "enum": [
                  "eltax_payeasy",
                  "etax_payeasy"
                ],
                "type": "string"
              },
              "lastAmountYen": {
                "type": "integer"
              },
              "lastPaidOn": {
                "format": "date",
                "type": "string"
              }
            },
            "required": [
              "kind",
              "bankLabel",
              "lastPaidOn",
              "lastAmountYen"
            ],
            "type": "object"
          },
          "confirmed": {
            "description": "The amount is the company’s own notice (保険料納入告知書), not an estimate.",
            "type": "boolean"
          },
          "items": {
            "items": {
              "properties": {
                "label": {
                  "example": "法人事業税",
                  "type": "string"
                },
                "yen": {
                  "example": 268200,
                  "type": "integer"
                }
              },
              "required": [
                "label",
                "yen"
              ],
              "type": "object"
            },
            "type": "array"
          },
          "key": {
            "example": "local",
            "type": "string"
          },
          "note": {
            "description": "What is specific to this payee.",
            "nullable": true,
            "type": "string"
          },
          "paid": {
            "description": "Paid in full, 30 days before to 14 days after the due date: one withdrawal of the whole amount, or one distinct withdrawal per line adding up to it (e-Tax takes 法人税 and 地方法人税 as two payments).",
            "nullable": true,
            "properties": {
              "amountYen": {
                "example": 998900,
                "type": "integer"
              },
              "lines": {
                "items": {
                  "properties": {
                    "amountYen": {
                      "example": 905700,
                      "type": "integer"
                    },
                    "bankTransactionId": {
                      "format": "uuid",
                      "type": "string"
                    },
                    "description": {
                      "example": "PE 渋谷税務署 26287001093",
                      "nullable": true,
                      "type": "string"
                    },
                    "journalEntryId": {
                      "format": "uuid",
                      "nullable": true,
                      "type": "string"
                    },
                    "paidOn": {
                      "format": "date",
                      "type": "string"
                    },
                    "pays": {
                      "description": "The line it paid (法人税（中間）); null when it paid the whole payee.",
                      "example": "法人税（中間）",
                      "nullable": true,
                      "type": "string"
                    },
                    "receipts": {
                      "description": "Files attached to the withdrawal (bank_transaction_evidence): the 控え of the payment.",
                      "items": {
                        "properties": {
                          "fileId": {
                            "format": "uuid",
                            "type": "string"
                          },
                          "fileName": {
                            "nullable": true,
                            "type": "string"
                          }
                        },
                        "required": [
                          "fileId",
                          "fileName"
                        ],
                        "type": "object"
                      },
                      "type": "array"
                    }
                  },
                  "required": [
                    "bankTransactionId",
                    "paidOn",
                    "amountYen",
                    "journalEntryId",
                    "description",
                    "pays",
                    "receipts"
                  ],
                  "type": "object"
                },
                "type": "array"
              },
              "paidOn": {
                "description": "The last of its withdrawals.",
                "format": "date",
                "type": "string"
              }
            },
            "required": [
              "paidOn",
              "amountYen",
              "lines"
            ],
            "type": "object"
          },
          "partial": {
            "description": "Some lines paid and others not. Never shown as paid; `note` names what is still owed.",
            "nullable": true,
            "properties": {
              "lines": {
                "items": {
                  "properties": {
                    "amountYen": {
                      "example": 905700,
                      "type": "integer"
                    },
                    "bankTransactionId": {
                      "format": "uuid",
                      "type": "string"
                    },
                    "description": {
                      "example": "PE 渋谷税務署 26287001093",
                      "nullable": true,
                      "type": "string"
                    },
                    "journalEntryId": {
                      "format": "uuid",
                      "nullable": true,
                      "type": "string"
                    },
                    "paidOn": {
                      "format": "date",
                      "type": "string"
                    },
                    "pays": {
                      "description": "The line it paid (法人税（中間）); null when it paid the whole payee.",
                      "example": "法人税（中間）",
                      "nullable": true,
                      "type": "string"
                    },
                    "receipts": {
                      "description": "Files attached to the withdrawal (bank_transaction_evidence): the 控え of the payment.",
                      "items": {
                        "properties": {
                          "fileId": {
                            "format": "uuid",
                            "type": "string"
                          },
                          "fileName": {
                            "nullable": true,
                            "type": "string"
                          }
                        },
                        "required": [
                          "fileId",
                          "fileName"
                        ],
                        "type": "object"
                      },
                      "type": "array"
                    }
                  },
                  "required": [
                    "bankTransactionId",
                    "paidOn",
                    "amountYen",
                    "journalEntryId",
                    "description",
                    "pays",
                    "receipts"
                  ],
                  "type": "object"
                },
                "type": "array"
              },
              "paidYen": {
                "example": 905700,
                "type": "integer"
              },
              "unpaid": {
                "items": {
                  "properties": {
                    "label": {
                      "example": "地方法人税（中間）",
                      "type": "string"
                    },
                    "yen": {
                      "example": 93200,
                      "type": "integer"
                    }
                  },
                  "required": [
                    "label",
                    "yen"
                  ],
                  "type": "object"
                },
                "type": "array"
              }
            },
            "required": [
              "paidYen",
              "lines",
              "unpaid"
            ],
            "type": "object"
          },
          "payYen": {
            "description": "What to pay: the saved 納付書 amount, else the estimate (totalYen).",
            "example": 465600,
            "type": "integer"
          },
          "payee": {
            "example": "都道府県（東京都は都税事務所）",
            "type": "string"
          },
          "receiptHint": {
            "description": "What to keep as the 控え of the payment (the e-Tax 即時通知 XML / 受信通知 PDF, the eLTAX 納付確認 PDF).",
            "nullable": true,
            "type": "string"
          },
          "route": {
            "description": "The 払い方 as numbered steps (each names its screen; buttons and on-screen labels are separate parts) and the values to enter, from the saved 納付書's lines. eltax_minashi leads with 「みなし・見込納付、更正・決定」.",
            "nullable": true,
            "properties": {
              "kind": {
                "enum": [
                  "eltax_minashi",
                  "eltax_efiled",
                  "etax"
                ],
                "type": "string"
              },
              "notes": {
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              "steps": {
                "items": {
                  "properties": {
                    "parts": {
                      "items": {
                        "properties": {
                          "kind": {
                            "description": "button = a button to press; label = words the screen shows (a menu, a status).",
                            "enum": [
                              "text",
                              "button",
                              "label"
                            ],
                            "type": "string"
                          },
                          "text": {
                            "example": "手入力による作成",
                            "type": "string"
                          }
                        },
                        "required": [
                          "kind",
                          "text"
                        ],
                        "type": "object"
                      },
                      "type": "array"
                    },
                    "screen": {
                      "example": "納付情報作成方法選択",
                      "type": "string"
                    }
                  },
                  "required": [
                    "screen",
                    "parts"
                  ],
                  "type": "object"
                },
                "type": "array"
              },
              "unverified": {
                "description": "Screen names not yet checked on a real screen (確認中).",
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              "values": {
                "items": {
                  "properties": {
                    "copyText": {
                      "description": "What the copy button copies (digits only for an amount); null unless entry is type.",
                      "example": "63300",
                      "nullable": true,
                      "type": "string"
                    },
                    "entry": {
                      "description": "type = typed in; choose = picked from a list; check = prefilled, only checked.",
                      "enum": [
                        "type",
                        "choose",
                        "check"
                      ],
                      "type": "string"
                    },
                    "label": {
                      "example": "法人都道府県民税 法人税割額",
                      "type": "string"
                    },
                    "value": {
                      "example": "63,300",
                      "type": "string"
                    }
                  },
                  "required": [
                    "label",
                    "value",
                    "entry",
                    "copyText"
                  ],
                  "type": "object"
                },
                "type": "array"
              },
              "valuesSource": {
                "description": "Where the amounts come from; null when no amounts are given.",
                "enum": [
                  "slip",
                  "estimate",
                  null
                ],
                "nullable": true,
                "type": "string"
              }
            },
            "required": [
              "kind",
              "steps",
              "values",
              "valuesSource",
              "notes",
              "unverified"
            ],
            "type": "object"
          },
          "slip": {
            "description": "The 納付書 the owner saved for this payee and due date.",
            "nullable": true,
            "properties": {
              "amountYen": {
                "example": 465600,
                "type": "integer"
              },
              "fileId": {
                "format": "uuid",
                "nullable": true,
                "type": "string"
              },
              "issuer": {
                "example": "東京都（渋谷都税事務所）",
                "nullable": true,
                "type": "string"
              },
              "lines": {
                "description": "The 納付書's own lines (its OCR), only when they add up to amountYen; else empty.",
                "items": {
                  "properties": {
                    "label": {
                      "example": "法人都民税 法人税割額",
                      "type": "string"
                    },
                    "yen": {
                      "example": 63300,
                      "type": "integer"
                    }
                  },
                  "required": [
                    "label",
                    "yen"
                  ],
                  "type": "object"
                },
                "type": "array"
              },
              "notificationId": {
                "format": "uuid",
                "type": "string"
              },
              "termEnd": {
                "format": "date",
                "nullable": true,
                "type": "string"
              },
              "termStart": {
                "description": "The 事業年度 printed on it.",
                "format": "date",
                "nullable": true,
                "type": "string"
              }
            },
            "required": [
              "notificationId",
              "fileId",
              "issuer",
              "amountYen",
              "lines",
              "termStart",
              "termEnd"
            ],
            "type": "object"
          },
          "totalYen": {
            "example": 465700,
            "type": "integer"
          }
        },
        "required": [
          "key",
          "payee",
          "totalYen",
          "items",
          "note"
        ],
        "type": "object"
      },
      "GuidanceSource": {
        "properties": {
          "title": {
            "type": "string"
          },
          "url": {
            "format": "uri",
            "type": "string"
          },
          "verifiedOn": {
            "description": "Date the page was loaded and the rule checked.",
            "format": "date",
            "type": "string"
          }
        },
        "required": [
          "url",
          "title",
          "verifiedOn"
        ],
        "type": "object"
      },
      "HabitReminder": {
        "properties": {
          "action": {
            "properties": {
              "kind": {
                "enum": [
                  "register_expenses",
                  "create_claim",
                  "create_payout",
                  "record_transfer",
                  "upload_evidence",
                  "review_bank"
                ],
                "type": "string"
              },
              "label": {
                "example": "9月の立替を登録する",
                "type": "string"
              },
              "path": {
                "example": "/expense-reports?group=wizard",
                "type": "string"
              }
            },
            "required": [
              "kind",
              "label",
              "path"
            ],
            "type": "object"
          },
          "amountYen": {
            "nullable": true,
            "type": "integer"
          },
          "cadence": {
            "enum": [
              "weekly",
              "biweekly",
              "monthly"
            ],
            "nullable": true,
            "type": "string"
          },
          "count": {
            "nullable": true,
            "type": "integer"
          },
          "daysOverdue": {
            "nullable": true,
            "type": "integer"
          },
          "detail": {
            "example": "5〜8月は毎月登録しています（月 61件・¥300,000前後）。2026/10/25 の精算に間に合わせるには、領収書を登録してください。",
            "type": "string"
          },
          "dueDate": {
            "description": "The payday or expected date it is measured against.",
            "format": "date",
            "nullable": true,
            "type": "string"
          },
          "evidence": {
            "description": "Why SBC thinks so: the months, claims or last dates behind the reminder.",
            "items": {
              "$ref": "#/components/schemas/HabitReminderEvidence"
            },
            "type": "array"
          },
          "id": {
            "description": "Stable per occurrence (`missing_month:2026-09`, `unpaid_pack:<uuid>` …): hiding 9月 never hides 10月.",
            "example": "missing_month:2026-09",
            "type": "string"
          },
          "kind": {
            "enum": [
              "missing_month",
              "unclaimed_receipts",
              "unpaid_reimbursement",
              "habit"
            ],
            "type": "string"
          },
          "title": {
            "example": "9月の立替がまだ0件です",
            "type": "string"
          },
          "tone": {
            "enum": [
              "danger",
              "warn",
              "info"
            ],
            "type": "string"
          }
        },
        "required": [
          "id",
          "kind",
          "tone",
          "title",
          "detail",
          "dueDate",
          "daysOverdue",
          "amountYen",
          "count",
          "cadence",
          "evidence",
          "action"
        ],
        "type": "object"
      },
      "HabitReminderDismissRequest": {
        "properties": {
          "id": {
            "maxLength": 200,
            "type": "string"
          },
          "snoozeDays": {
            "description": "Omit to hide this occurrence for good.",
            "maximum": 30,
            "minimum": 1,
            "type": "integer"
          }
        },
        "required": [
          "id"
        ],
        "type": "object"
      },
      "HabitReminderDismissResult": {
        "properties": {
          "applied": {
            "type": "boolean"
          },
          "id": {
            "type": "string"
          },
          "reason": {
            "description": "stale: not a current reminder, nothing stored.",
            "enum": [
              "stale"
            ],
            "nullable": true,
            "type": "string"
          },
          "until": {
            "description": "Snoozed until this JST date; null = hidden for good.",
            "format": "date",
            "nullable": true,
            "type": "string"
          }
        },
        "required": [
          "id",
          "applied",
          "until",
          "reason"
        ],
        "type": "object"
      },
      "HabitReminderEvidence": {
        "properties": {
          "amountYen": {
            "example": 365968,
            "nullable": true,
            "type": "integer"
          },
          "date": {
            "example": "2026-08-01",
            "format": "date",
            "type": "string"
          },
          "label": {
            "example": "2026年8月 66件",
            "type": "string"
          }
        },
        "required": [
          "date",
          "label",
          "amountYen"
        ],
        "type": "object"
      },
      "HabitReminderSummary": {
        "properties": {
          "nextPayday": {
            "example": "2026-10-25",
            "format": "date",
            "type": "string"
          },
          "owedTotalYen": {
            "description": "Current-FY 立替 still owed to the officer.",
            "type": "integer"
          },
          "payday": {
            "example": 25,
            "maximum": 31,
            "minimum": 1,
            "type": "integer"
          },
          "today": {
            "description": "JST date the reminders were computed for.",
            "format": "date",
            "type": "string"
          }
        },
        "required": [
          "today",
          "payday",
          "nextPayday",
          "owedTotalYen"
        ],
        "type": "object"
      },
      "HealthStatusResponse": {
        "properties": {
          "data": {
            "properties": {
              "status": {
                "example": "healthy",
                "type": "string"
              },
              "timestamp": {
                "example": "2024-01-15T10:30:00.000Z",
                "format": "date-time",
                "type": "string"
              },
              "uptime": {
                "example": 3600,
                "type": "number"
              },
              "version": {
                "example": "1.0.0",
                "type": "string"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Service is healthy",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "type": "object"
      },
      "HomeInitResponse": {
        "description": "Composite response combining all homepage data sources",
        "properties": {
          "data": {
            "properties": {
              "bankOverview": {
                "description": "Bank statements overview (銀行取引概要)",
                "nullable": true,
                "properties": {
                  "accounts": {
                    "items": {
                      "type": "object"
                    },
                    "type": "array"
                  },
                  "summary": {
                    "type": "object"
                  },
                  "syncStatus": {
                    "type": "object"
                  }
                },
                "type": "object"
              },
              "dockSummary": {
                "description": "Accounting dock summary (仕訳・元帳・試算表の進捗)",
                "nullable": true,
                "properties": {
                  "generalLedger": {
                    "properties": {
                      "posted": {
                        "example": 100,
                        "type": "integer"
                      },
                      "total": {
                        "example": 120,
                        "type": "integer"
                      }
                    },
                    "type": "object"
                  },
                  "journal": {
                    "properties": {
                      "draft": {
                        "example": 30,
                        "type": "integer"
                      },
                      "posted": {
                        "example": 120,
                        "type": "integer"
                      },
                      "total": {
                        "example": 150,
                        "type": "integer"
                      }
                    },
                    "type": "object"
                  },
                  "pendingDraftsCount": {
                    "example": 5,
                    "type": "integer"
                  },
                  "sources": {
                    "properties": {
                      "bankStatements": {
                        "example": 125,
                        "type": "integer"
                      },
                      "expenses": {
                        "example": 30,
                        "type": "integer"
                      }
                    },
                    "type": "object"
                  },
                  "trialBalance": {
                    "properties": {
                      "isBalanced": {
                        "example": true,
                        "type": "boolean"
                      },
                      "totalCredit": {
                        "example": 5000000,
                        "type": "integer"
                      },
                      "totalDebit": {
                        "example": 5000000,
                        "type": "integer"
                      }
                    },
                    "type": "object"
                  }
                },
                "type": "object"
              },
              "documentStatistics": {
                "additionalProperties": {
                  "type": "integer"
                },
                "description": "Document counts by type (書類タイプ別件数)",
                "example": {
                  "payment": 8,
                  "purchase_order": 5,
                  "sales_invoice": 12
                },
                "nullable": true,
                "type": "object"
              },
              "financialSummary": {
                "description": "Financial summary (試算表・損益計算書・貸借対照表)",
                "nullable": true,
                "properties": {
                  "balanceSheet": {
                    "description": "Balance sheet data",
                    "type": "object"
                  },
                  "generatedAt": {
                    "format": "date-time",
                    "type": "string"
                  },
                  "profitLoss": {
                    "description": "Profit & loss statement data",
                    "type": "object"
                  },
                  "trialBalance": {
                    "description": "Trial balance data",
                    "type": "object"
                  }
                },
                "type": "object"
              },
              "recentDocuments": {
                "description": "Most recently updated documents (最新の書類)",
                "nullable": true,
                "properties": {
                  "items": {
                    "items": {
                      "type": "object"
                    },
                    "type": "array"
                  },
                  "pagination": {
                    "properties": {
                      "currentPage": {
                        "example": 1,
                        "type": "integer"
                      },
                      "pageSize": {
                        "example": 8,
                        "type": "integer"
                      },
                      "totalItems": {
                        "example": 50,
                        "type": "integer"
                      },
                      "totalPages": {
                        "example": 7,
                        "type": "integer"
                      }
                    },
                    "type": "object"
                  }
                },
                "type": "object"
              }
            },
            "type": "object"
          },
          "meta": {
            "description": "Response metadata",
            "properties": {
              "cached": {
                "description": "Whether response was served from memory cache",
                "type": "boolean"
              },
              "durationMs": {
                "description": "Total query time in milliseconds",
                "example": 350,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "type": "object"
      },
      "HoteiChoshoGenerateRequest": {
        "description": "Request body for generating 法定調書合計表 XML with selective inclusion.\n\n**Data Sources:**\n- `include_salary_slip_ids`: Document IDs from the documents table (document_type='salary_slip')\n- `include_withholding_ids`: Record IDs from the withholding_taxes table\n\n**Behavior:**\n- If arrays are empty/undefined: ALL eligible records for the year are included\n- If arrays have values: ONLY those specific records are included\n\n**Frontend Integration:**\nGet IDs from the preview endpoint response:\n- `categories.salary.employees[].records[].documentId` → use for `include_salary_slip_ids`\n- `categories.freelance/royalty/other[].id` → use for `include_withholding_ids`",
        "properties": {
          "include_salary_slip_ids": {
            "description": "Document IDs for salary_slip documents to include (from documents table). Max 500 items.",
            "example": [
              "550e8400-e29b-41d4-a716-446655440000"
            ],
            "items": {
              "format": "uuid",
              "type": "string"
            },
            "maxItems": 500,
            "type": "array"
          },
          "include_withholding_ids": {
            "description": "Record IDs from withholding_taxes table to include (freelance, royalty, etc.). Max 500 items.",
            "example": [
              "550e8400-e29b-41d4-a716-446655440001"
            ],
            "items": {
              "format": "uuid",
              "type": "string"
            },
            "maxItems": 500,
            "type": "array"
          },
          "year": {
            "description": "Tax year for the hotei chosho total",
            "example": 2025,
            "maximum": 2030,
            "minimum": 2020,
            "type": "integer"
          }
        },
        "required": [
          "year"
        ],
        "type": "object"
      },
      "HoteiChoshoPreviewResponse": {
        "properties": {
          "data": {
            "properties": {
              "categories": {
                "properties": {
                  "freelance": {
                    "properties": {
                      "records": {
                        "items": {
                          "properties": {
                            "description": {
                              "nullable": true,
                              "type": "string"
                            },
                            "grossAmount": {
                              "example": 100000,
                              "type": "number"
                            },
                            "id": {
                              "format": "uuid",
                              "type": "string"
                            },
                            "payeeName": {
                              "example": "田中デザイン事務所",
                              "type": "string"
                            },
                            "payeeType": {
                              "type": "string"
                            },
                            "paymentDate": {
                              "type": "integer"
                            },
                            "status": {
                              "enum": [
                                "paid",
                                "pending"
                              ],
                              "type": "string"
                            },
                            "withholdingAmount": {
                              "example": 10210,
                              "type": "number"
                            }
                          },
                          "type": "object"
                        },
                        "type": "array"
                      },
                      "subtotal": {
                        "properties": {
                          "amount": {
                            "type": "number"
                          },
                          "count": {
                            "type": "integer"
                          },
                          "tax": {
                            "type": "number"
                          }
                        },
                        "type": "object"
                      }
                    },
                    "type": "object"
                  },
                  "other": {
                    "description": "Same structure as freelance",
                    "type": "object"
                  },
                  "royalty": {
                    "description": "Same structure as freelance",
                    "type": "object"
                  },
                  "salary": {
                    "properties": {
                      "employees": {
                        "items": {
                          "properties": {
                            "employeeAddress": {
                              "nullable": true,
                              "type": "string"
                            },
                            "employeeId": {
                              "description": "employees.id when identity is employee_id; the payee name for a legacy name-only group",
                              "type": "string"
                            },
                            "employeeName": {
                              "example": "代表太郎",
                              "type": "string"
                            },
                            "identity": {
                              "description": "How the group was keyed (BL-219). name = rows without an employee id, grouped by name",
                              "enum": [
                                "employee_id",
                                "name"
                              ],
                              "type": "string"
                            },
                            "myNumber": {
                              "example": "********1234",
                              "nullable": true,
                              "type": "string"
                            },
                            "records": {
                              "items": {
                                "properties": {
                                  "bankTransactionId": {
                                    "description": "Linked bank transaction ID for salary payment confirmation (給与支払い確認用)",
                                    "format": "uuid",
                                    "nullable": true,
                                    "type": "string"
                                  },
                                  "documentId": {
                                    "format": "uuid",
                                    "nullable": true,
                                    "type": "string"
                                  },
                                  "grossAmount": {
                                    "example": 200000,
                                    "type": "number"
                                  },
                                  "id": {
                                    "format": "uuid",
                                    "type": "string"
                                  },
                                  "isTaxable": {
                                    "description": "Whether this payment is taxable income (true for salary/bonus, false for reimbursements)",
                                    "type": "boolean"
                                  },
                                  "linkedDocuments": {
                                    "description": "Linked documents for document flow display (給与明細→支払明細→銀行取引)",
                                    "properties": {
                                      "paymentId": {
                                        "description": "支払明細書 document ID",
                                        "format": "uuid",
                                        "nullable": true,
                                        "type": "string"
                                      },
                                      "paymentName": {
                                        "example": "20260125_支払明細書_JPY250000",
                                        "nullable": true,
                                        "type": "string"
                                      },
                                      "salarySlipId": {
                                        "description": "給与明細書 document ID",
                                        "format": "uuid",
                                        "nullable": true,
                                        "type": "string"
                                      },
                                      "salarySlipName": {
                                        "example": "20260125_給与明細書_JPY250000_代表太郎",
                                        "nullable": true,
                                        "type": "string"
                                      }
                                    },
                                    "type": "object"
                                  },
                                  "paidAt": {
                                    "nullable": true,
                                    "type": "string"
                                  },
                                  "paySlipId": {
                                    "format": "uuid",
                                    "nullable": true,
                                    "type": "string"
                                  },
                                  "paymentCategory": {
                                    "description": "Payment type classification for tax purposes",
                                    "enum": [
                                      "salary",
                                      "director_salary",
                                      "bonus",
                                      "expense_reimbursement",
                                      "travel_settlement",
                                      "advance_settlement",
                                      "freelance_fee",
                                      "unknown"
                                    ],
                                    "type": "string"
                                  },
                                  "paymentDate": {
                                    "nullable": true,
                                    "type": "integer"
                                  },
                                  "period": {
                                    "example": "2025年12月分",
                                    "type": "string"
                                  },
                                  "socialInsuranceAmount": {
                                    "description": "社会保険料合計 (健康保険+厚生年金+介護保険+雇用保険)",
                                    "example": 16209,
                                    "type": "number"
                                  },
                                  "sourceDocumentName": {
                                    "description": "Document name for display and linking",
                                    "example": "20260125_給与明細書_JPY250000_代表太郎",
                                    "nullable": true,
                                    "type": "string"
                                  },
                                  "status": {
                                    "description": "Salary payment status (給与支払い状態)",
                                    "enum": [
                                      "paid",
                                      "pending",
                                      "draft"
                                    ],
                                    "type": "string"
                                  },
                                  "taxPaymentBankTransactionId": {
                                    "description": "Linked bank transaction ID for tax office payment (税務署への納付用) - only set when actual tax payment is linked",
                                    "format": "uuid",
                                    "nullable": true,
                                    "type": "string"
                                  },
                                  "taxPaymentStatus": {
                                    "description": "Tax office payment status (税務署への納付状態) - null if no linked withholding record",
                                    "enum": [
                                      "paid",
                                      "pending",
                                      "scheduled",
                                      "late",
                                      "cancelled"
                                    ],
                                    "nullable": true,
                                    "type": "string"
                                  },
                                  "withholdingAmount": {
                                    "example": 15300,
                                    "type": "number"
                                  }
                                },
                                "type": "object"
                              },
                              "type": "array"
                            },
                            "ytd": {
                              "properties": {
                                "grossTotal": {
                                  "example": 800000,
                                  "type": "number"
                                },
                                "socialInsuranceTotal": {
                                  "description": "社会保険料合計 (健康保険+厚生年金+介護保険+雇用保険)",
                                  "example": 64836,
                                  "type": "number"
                                },
                                "taxTotal": {
                                  "example": 61200,
                                  "type": "number"
                                }
                              },
                              "type": "object"
                            }
                          },
                          "type": "object"
                        },
                        "type": "array"
                      },
                      "subtotal": {
                        "properties": {
                          "amount": {
                            "example": 800000,
                            "type": "number"
                          },
                          "persons": {
                            "example": 1,
                            "type": "integer"
                          },
                          "socialInsurance": {
                            "description": "社会保険料合計 (健康保険+厚生年金+介護保険+雇用保険)",
                            "example": 64836,
                            "type": "number"
                          },
                          "tax": {
                            "example": 61200,
                            "type": "number"
                          }
                        },
                        "type": "object"
                      }
                    },
                    "type": "object"
                  }
                },
                "type": "object"
              },
              "grandTotal": {
                "properties": {
                  "amount": {
                    "example": 950000,
                    "type": "number"
                  },
                  "tax": {
                    "example": 76515,
                    "type": "number"
                  }
                },
                "type": "object"
              },
              "taxableSummary": {
                "description": "Breakdown of taxable vs non-taxable payments for 法定調書 filing",
                "properties": {
                  "nonTaxableAmount": {
                    "description": "非課税合計 - Total non-taxable payments (expense reimbursements, travel settlements)",
                    "example": 150000,
                    "type": "number"
                  },
                  "nonTaxableRecordCount": {
                    "description": "Number of non-taxable payment records",
                    "example": 2,
                    "type": "integer"
                  },
                  "taxableAmount": {
                    "description": "課税対象合計 - Total taxable income (salary, bonus, director compensation)",
                    "example": 800000,
                    "type": "number"
                  },
                  "taxableRecordCount": {
                    "description": "Number of taxable payment records",
                    "example": 4,
                    "type": "integer"
                  },
                  "taxableTax": {
                    "description": "課税対象の源泉徴収税額 - Total withholding tax on taxable income",
                    "example": 61200,
                    "type": "number"
                  }
                },
                "type": "object"
              },
              "warnings": {
                "items": {
                  "properties": {
                    "message": {
                      "example": "下書き状態の給与明細は合計に含まれません",
                      "type": "string"
                    },
                    "recordIds": {
                      "items": {
                        "format": "uuid",
                        "type": "string"
                      },
                      "type": "array"
                    },
                    "type": {
                      "description": "payee_keyed_by_name: rows without an employee id, grouped by or attached by name. possible_same_name_payees: a name shared by several employees, or one name group with differing My Numbers / addresses (BL-219)",
                      "enum": [
                        "draft_excluded",
                        "missing_address",
                        "missing_mynumber",
                        "unpaid",
                        "payee_keyed_by_name",
                        "possible_same_name_payees"
                      ],
                      "type": "string"
                    }
                  },
                  "type": "object"
                },
                "type": "array"
              },
              "year": {
                "example": 2025,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "2025年度の法定調書合計表プレビューを取得しました",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "type": "object"
      },
      "HoteiChoshoTotalRequest": {
        "properties": {
          "year": {
            "description": "Tax year for the hotei chosho total",
            "example": 2024,
            "maximum": 2030,
            "minimum": 2020,
            "type": "integer"
          }
        },
        "required": [
          "year"
        ],
        "type": "object"
      },
      "ImageProcessingJob": {
        "properties": {
          "aiData": {
            "additionalProperties": true,
            "description": "The persisted AI extraction (session_files.ai_data) once the job completed — the same object the file_processing_completed SSE event carries, so a client that missed the event can poll it.",
            "type": "object"
          },
          "completedAt": {
            "description": "Job completion timestamp",
            "example": "2024-01-15T10:32:15.000Z",
            "format": "date-time",
            "type": "string"
          },
          "createdAt": {
            "description": "Job creation timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "error": {
            "description": "Error message if processing failed",
            "example": "Failed to extract text from image",
            "type": "string"
          },
          "fileName": {
            "description": "Generated file name for processing",
            "example": "processed_image_20240115_103000.jpg",
            "type": "string"
          },
          "id": {
            "description": "Job unique identifier",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "mimeType": {
            "description": "File MIME type (validated by magic bytes)",
            "enum": [
              "image/jpeg",
              "image/png",
              "image/gif",
              "image/webp",
              "application/pdf",
              "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
            ],
            "example": "image/jpeg",
            "type": "string"
          },
          "originalName": {
            "description": "Original uploaded file name",
            "example": "receipt_scan.jpg",
            "type": "string"
          },
          "status": {
            "description": "Current job processing status",
            "enum": [
              "pending",
              "processing",
              "completed",
              "failed"
            ],
            "example": "completed",
            "type": "string"
          },
          "suggestedName": {
            "description": "AI-suggested file name based on content analysis",
            "example": "restaurant_receipt_2024_01_15.jpg",
            "type": "string"
          }
        },
        "required": [
          "id",
          "fileName",
          "originalName",
          "mimeType",
          "status",
          "createdAt"
        ],
        "type": "object"
      },
      "ImportError": {
        "properties": {
          "description": {
            "description": "Description of the problematic entry",
            "example": "売上計上",
            "type": "string"
          },
          "entry_date": {
            "description": "Entry date of the problematic entry",
            "example": 20260115,
            "type": "integer"
          },
          "entry_index": {
            "description": "Index of the entry with error",
            "example": 0,
            "type": "integer"
          },
          "error_code": {
            "description": "Error code",
            "example": "ACCOUNT_NOT_FOUND",
            "type": "string"
          },
          "error_message": {
            "description": "Human-readable error message",
            "example": "勘定科目コード「9999」が見つかりません (Account code not found)",
            "type": "string"
          },
          "line_index": {
            "description": "Index of the line with error (if applicable)",
            "example": 0,
            "type": "integer"
          }
        },
        "required": [
          "entry_index",
          "error_code",
          "error_message"
        ],
        "type": "object"
      },
      "ImportFromTextRequest": {
        "properties": {
          "text": {
            "description": "Raw bank statement text to parse and import",
            "example": "2024/01/15 振込 タナカ タロウ 300,000 1,250,000\n2024/01/16 ATM出金 -50,000 1,200,000\n2024/01/17 カード決済 コンビニ -1,200 1,198,800",
            "maxLength": 50000,
            "minLength": 10,
            "type": "string"
          }
        },
        "required": [
          "text"
        ],
        "type": "object"
      },
      "ImportJournalEntriesRequest": {
        "properties": {
          "entries": {
            "description": "Array of journal entries to import",
            "items": {
              "$ref": "#/components/schemas/ImportJournalEntry"
            },
            "minItems": 1,
            "type": "array"
          },
          "filename": {
            "description": "Original filename for audit trail",
            "example": "yayoi_export_2026.csv",
            "type": "string"
          },
          "source": {
            "$ref": "#/components/schemas/ImportSourceType"
          }
        },
        "required": [
          "entries",
          "source",
          "filename"
        ],
        "type": "object"
      },
      "ImportJournalEntriesResponse": {
        "properties": {
          "data": {
            "properties": {
              "errors": {
                "description": "Array of import errors",
                "items": {
                  "$ref": "#/components/schemas/ImportError"
                },
                "type": "array"
              },
              "imported_count": {
                "description": "Number of successfully imported entries",
                "example": 15,
                "type": "integer"
              },
              "imported_entry_ids": {
                "description": "IDs of successfully imported entries",
                "items": {
                  "format": "uuid",
                  "type": "string"
                },
                "type": "array"
              },
              "skipped_count": {
                "description": "Number of skipped entries due to errors",
                "example": 0,
                "type": "integer"
              }
            },
            "required": [
              "imported_count",
              "skipped_count",
              "errors",
              "imported_entry_ids"
            ],
            "type": "object"
          },
          "message": {
            "example": "15件の仕訳をインポートしました (Imported 15 journal entries)",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ImportJournalEntry": {
        "properties": {
          "description": {
            "description": "Journal entry description",
            "example": "売上計上",
            "type": "string"
          },
          "entry_date": {
            "description": "Entry date in YYYYMMDD format",
            "example": 20260115,
            "type": "integer"
          },
          "lines": {
            "description": "Journal entry lines (minimum 2 for debit/credit)",
            "items": {
              "$ref": "#/components/schemas/ImportJournalLine"
            },
            "minItems": 2,
            "type": "array"
          }
        },
        "required": [
          "entry_date",
          "description",
          "lines"
        ],
        "type": "object"
      },
      "ImportJournalLine": {
        "properties": {
          "account_code": {
            "description": "Account code (will be resolved to account_id)",
            "example": "4100",
            "type": "string"
          },
          "account_name": {
            "description": "Optional account name for validation",
            "example": "売上高",
            "type": "string"
          },
          "consumption_tax_rate": {
            "description": "Consumption tax rate",
            "enum": [
              "10%",
              "8%",
              "0%",
              "exempt",
              "non_taxable"
            ],
            "example": "10%",
            "type": "string"
          },
          "credit_amount": {
            "description": "貸方金額 (Credit amount)",
            "example": 0,
            "minimum": 0,
            "type": "number"
          },
          "debit_amount": {
            "description": "借方金額 (Debit amount)",
            "example": 110000,
            "minimum": 0,
            "type": "number"
          },
          "description": {
            "description": "Line item description",
            "example": "商品売上",
            "type": "string"
          },
          "tax_code": {
            "description": "Tax code",
            "example": 10,
            "type": "integer"
          }
        },
        "required": [
          "account_code",
          "debit_amount",
          "credit_amount"
        ],
        "type": "object"
      },
      "ImportSourceType": {
        "description": "Source accounting software for import",
        "enum": [
          "moneyforward",
          "freee",
          "yayoi",
          "pca",
          "jdl",
          "mjs",
          "tkc",
          "kanjo_bugyo",
          "zaimu_ouen",
          "kaikei_oh",
          "yaruzo_aoiro",
          "jdl_ibex_suito",
          "a_saas",
          "cash_radar",
          "generic"
        ],
        "example": "yayoi",
        "type": "string"
      },
      "IngestFromExpenses": {
        "properties": {
          "dryRun": {
            "default": true,
            "type": "boolean"
          },
          "expenseIds": {
            "items": {
              "format": "uuid",
              "type": "string"
            },
            "type": "array"
          }
        },
        "type": "object"
      },
      "InitiateRecoveryRequest": {
        "properties": {
          "email": {
            "description": "Primary or backup email to recover",
            "format": "email",
            "type": "string"
          }
        },
        "required": [
          "email"
        ],
        "type": "object"
      },
      "Inkan": {
        "properties": {
          "created_at": {
            "description": "Creation timestamp",
            "example": "2026-01-07T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "description": {
            "description": "Optional description for the inkan",
            "example": "Main company registered seal",
            "nullable": true,
            "type": "string"
          },
          "file_name": {
            "description": "Original uploaded file name",
            "example": "company_seal.png",
            "type": "string"
          },
          "file_size": {
            "description": "File size in bytes",
            "example": 102400,
            "nullable": true,
            "type": "integer"
          },
          "file_url": {
            "description": "Public URL to access the inkan image",
            "example": "https://supabase.co/storage/v1/object/public/inkans/user123/jitsuin_seal.png",
            "format": "uri",
            "type": "string"
          },
          "id": {
            "description": "Unique inkan identifier",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "inkan_type": {
            "description": "Type of corporate seal",
            "enum": [
              "jitsuin",
              "ginkoin",
              "kakuin"
            ],
            "example": "jitsuin",
            "type": "string"
          },
          "is_active": {
            "description": "Whether this inkan is currently active",
            "example": true,
            "type": "boolean"
          },
          "mime_type": {
            "description": "MIME type of the uploaded file",
            "example": "image/png",
            "nullable": true,
            "type": "string"
          },
          "updated_at": {
            "description": "Last update timestamp",
            "example": "2026-01-07T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          }
        },
        "required": [
          "id",
          "inkan_type",
          "file_name",
          "file_url",
          "is_active",
          "created_at",
          "updated_at"
        ],
        "type": "object"
      },
      "InkanListResponse": {
        "properties": {
          "data": {
            "items": {
              "$ref": "#/components/schemas/Inkan"
            },
            "type": "array"
          },
          "message": {
            "example": "Inkans retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "type": "object"
      },
      "InkanResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/Inkan"
          },
          "message": {
            "example": "Inkan retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "type": "object"
      },
      "InkanTypeInfo": {
        "properties": {
          "description": {
            "description": "Usage description",
            "example": "Official seal registered at Legal Affairs Bureau. Used for contracts and official documents.",
            "type": "string"
          },
          "en": {
            "description": "English name",
            "example": "Corporate Registered Seal",
            "type": "string"
          },
          "ja": {
            "description": "Japanese name",
            "example": "実印（代表取締役印）",
            "type": "string"
          },
          "type": {
            "description": "Inkan type identifier",
            "enum": [
              "jitsuin",
              "ginkoin",
              "kakuin"
            ],
            "type": "string"
          }
        },
        "type": "object"
      },
      "InkansForDocument": {
        "description": "Inkan URLs formatted for document template integration",
        "properties": {
          "ginkoin_url": {
            "description": "URL to ginkoin (bank seal) image",
            "example": "https://supabase.co/storage/v1/object/public/inkans/user123/ginkoin_seal.png",
            "format": "uri",
            "nullable": true,
            "type": "string"
          },
          "jitsuin_url": {
            "description": "URL to jitsuin (registered seal) image",
            "example": "https://supabase.co/storage/v1/object/public/inkans/user123/jitsuin_seal.png",
            "format": "uri",
            "nullable": true,
            "type": "string"
          },
          "kakuin_url": {
            "description": "URL to kakuin (square seal) image",
            "example": "https://supabase.co/storage/v1/object/public/inkans/user123/kakuin_seal.png",
            "format": "uri",
            "nullable": true,
            "type": "string"
          }
        },
        "required": [
          "jitsuin_url",
          "ginkoin_url",
          "kakuin_url"
        ],
        "type": "object"
      },
      "InkansForDocumentResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/InkansForDocument"
          },
          "message": {
            "example": "Inkans for document retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "type": "object"
      },
      "InsightCountsResponse": {
        "properties": {
          "counts": {
            "properties": {
              "high": {
                "example": 2,
                "type": "integer"
              },
              "low": {
                "example": 3,
                "type": "integer"
              },
              "medium": {
                "example": 5,
                "type": "integer"
              },
              "urgent": {
                "example": 0,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "total": {
            "example": 10,
            "type": "integer"
          }
        },
        "type": "object"
      },
      "InsurancePremiumInput": {
        "properties": {
          "employment_insurance_employee": {
            "minimum": 0,
            "type": "number"
          },
          "employment_insurance_employer": {
            "minimum": 0,
            "type": "number"
          },
          "health_insurance_employee": {
            "minimum": 0,
            "type": "number"
          },
          "health_insurance_employer": {
            "minimum": 0,
            "type": "number"
          },
          "pension_employee": {
            "minimum": 0,
            "type": "number"
          },
          "pension_employer": {
            "minimum": 0,
            "type": "number"
          },
          "year_month": {
            "description": "YYYYMM format",
            "type": "integer"
          }
        },
        "required": [
          "year_month"
        ],
        "type": "object"
      },
      "IntegrationBatch": {
        "additionalProperties": false,
        "properties": {
          "approvedAt": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "bankStatementId": {
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "batchDate": {
            "description": "YYYYMMDD",
            "nullable": true,
            "type": "integer"
          },
          "batchId": {
            "description": "tsumagoi batch id, Stripe payout id, yen-yen transaction id",
            "type": "string"
          },
          "claimDocumentId": {
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "createdAt": {
            "format": "date-time",
            "type": "string"
          },
          "entries": {
            "items": {
              "additionalProperties": false,
              "properties": {
                "description": {
                  "type": "string"
                },
                "entryDate": {
                  "type": "integer"
                },
                "entryNumber": {
                  "type": "string"
                },
                "id": {
                  "format": "uuid",
                  "type": "string"
                },
                "lines": {
                  "items": {
                    "additionalProperties": false,
                    "properties": {
                      "accountCode": {
                        "type": "string"
                      },
                      "accountName": {
                        "type": "string"
                      },
                      "credit": {
                        "type": "number"
                      },
                      "debit": {
                        "type": "number"
                      },
                      "description": {
                        "nullable": true,
                        "type": "string"
                      },
                      "lineNumber": {
                        "type": "integer"
                      },
                      "taxCode": {
                        "nullable": true,
                        "type": "integer"
                      },
                      "taxRate": {
                        "nullable": true,
                        "type": "string"
                      }
                    },
                    "required": [
                      "lineNumber",
                      "accountCode",
                      "accountName",
                      "debit",
                      "credit",
                      "description",
                      "taxCode",
                      "taxRate"
                    ],
                    "type": "object"
                  },
                  "type": "array"
                },
                "status": {
                  "enum": [
                    "draft",
                    "posted",
                    "reversed",
                    "deleted"
                  ],
                  "type": "string"
                }
              },
              "required": [
                "id",
                "entryNumber",
                "entryDate",
                "description",
                "status",
                "lines"
              ],
              "type": "object"
            },
            "type": "array"
          },
          "error": {
            "nullable": true,
            "type": "string"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "kind": {
            "description": "sales_day | payout | cash_close | stock_close | disposal | purchase | reimbursable",
            "type": "string"
          },
          "lateReceipt": {
            "type": "boolean"
          },
          "seq": {
            "nullable": true,
            "type": "integer"
          },
          "source": {
            "enum": [
              "tsumagoi",
              "yen_yen",
              "stripe"
            ],
            "type": "string"
          },
          "status": {
            "enum": [
              "drafted",
              "approved",
              "skipped",
              "failed",
              "superseded"
            ],
            "type": "string"
          },
          "version": {
            "type": "integer"
          }
        },
        "required": [
          "id",
          "source",
          "batchId",
          "version",
          "seq",
          "kind",
          "status",
          "batchDate",
          "error",
          "bankStatementId",
          "claimDocumentId",
          "lateReceipt",
          "approvedAt",
          "createdAt",
          "entries"
        ],
        "type": "object"
      },
      "IntegrationClaimDuplicate": {
        "additionalProperties": false,
        "properties": {
          "counterparts": {
            "items": {
              "additionalProperties": false,
              "properties": {
                "amount": {
                  "type": "number"
                },
                "date": {
                  "description": "YYYYMMDD",
                  "nullable": true,
                  "type": "integer"
                },
                "id": {
                  "format": "uuid",
                  "type": "string"
                },
                "isVoided": {
                  "type": "boolean"
                },
                "name": {
                  "nullable": true,
                  "type": "string"
                },
                "purpose": {
                  "nullable": true,
                  "type": "string"
                },
                "source": {
                  "description": "yen_yen | tsumagoi",
                  "nullable": true,
                  "type": "string"
                },
                "status": {
                  "description": "documents.status (draft while held)",
                  "type": "string"
                },
                "vendor": {
                  "nullable": true,
                  "type": "string"
                }
              },
              "required": [
                "id",
                "name",
                "source",
                "amount",
                "date",
                "vendor",
                "purpose",
                "status",
                "isVoided"
              ],
              "type": "object"
            },
            "type": "array"
          },
          "decision": {
            "description": "The decision a resumed review must repeat (an earlier run already voided or reversed something); null when any decision is allowed",
            "enum": [
              "keep_flagged",
              "keep_counterparts",
              "distinct"
            ],
            "nullable": true,
            "type": "string"
          },
          "detectedAt": {
            "format": "date-time",
            "type": "string"
          },
          "flagged": {
            "additionalProperties": false,
            "properties": {
              "amount": {
                "type": "number"
              },
              "date": {
                "description": "YYYYMMDD",
                "nullable": true,
                "type": "integer"
              },
              "id": {
                "format": "uuid",
                "type": "string"
              },
              "isVoided": {
                "type": "boolean"
              },
              "name": {
                "nullable": true,
                "type": "string"
              },
              "purpose": {
                "nullable": true,
                "type": "string"
              },
              "source": {
                "description": "yen_yen | tsumagoi",
                "nullable": true,
                "type": "string"
              },
              "status": {
                "description": "documents.status (draft while held)",
                "type": "string"
              },
              "vendor": {
                "nullable": true,
                "type": "string"
              }
            },
            "required": [
              "id",
              "name",
              "source",
              "amount",
              "date",
              "vendor",
              "purpose",
              "status",
              "isVoided"
            ],
            "type": "object"
          },
          "held": {
            "description": "Created as a draft without 仕訳 because of the match",
            "type": "boolean"
          },
          "kind": {
            "description": "exact amount / amounts add up / fits inside a larger charge",
            "enum": [
              "exact",
              "sum",
              "contained"
            ],
            "type": "string"
          },
          "stage": {
            "description": "open; resolving (a decision is running); stalled (a decision died — resolve again with the same decision); unpublished (decided to keep a held claim but publishing failed — resolve again resumes it); finishing (this claim was voided by its own keep_counterparts, which stopped before its clean-up — resolve keep_counterparts finishes it); decided",
            "enum": [
              "open",
              "resolving",
              "stalled",
              "unpublished",
              "finishing",
              "decided"
            ],
            "type": "string"
          },
          "status": {
            "enum": [
              "open",
              "resolving",
              "kept",
              "distinct",
              "voided",
              "closed"
            ],
            "type": "string"
          }
        },
        "required": [
          "flagged",
          "counterparts",
          "kind",
          "held",
          "status",
          "stage",
          "decision",
          "detectedAt"
        ],
        "type": "object"
      },
      "IntegrationSource": {
        "additionalProperties": false,
        "properties": {
          "claimMode": {
            "description": "立替の正とする連携: detail_only = item detail (inventory) only, no 立替 claim — the other integration is the payment truth (tsumagoi only)",
            "enum": [
              "claim",
              "detail_only"
            ],
            "type": "string"
          },
          "cursor": {
            "description": "Source cursor: tsumagoi seq, yen-yen updated_at|id, Stripe unix seconds",
            "nullable": true,
            "type": "string"
          },
          "enabled": {
            "type": "boolean"
          },
          "endpoint": {
            "nullable": true,
            "type": "string"
          },
          "hasToken": {
            "description": "A token is stored (it is never returned)",
            "type": "boolean"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "lastError": {
            "nullable": true,
            "type": "string"
          },
          "lastPulledAt": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "source": {
            "enum": [
              "tsumagoi",
              "yen_yen",
              "stripe"
            ],
            "type": "string"
          },
          "updatedAt": {
            "format": "date-time",
            "type": "string"
          }
        },
        "required": [
          "id",
          "source",
          "endpoint",
          "hasToken",
          "enabled",
          "cursor",
          "lastPulledAt",
          "lastError",
          "claimMode",
          "updatedAt"
        ],
        "type": "object"
      },
      "IntegrationStatus": {
        "additionalProperties": false,
        "properties": {
          "draftsAwaitingApproval": {
            "type": "integer"
          },
          "failedBatches": {
            "type": "integer"
          },
          "lateReceipts": {
            "items": {
              "additionalProperties": false,
              "properties": {
                "batchLogId": {
                  "format": "uuid",
                  "type": "string"
                },
                "occurredOn": {
                  "nullable": true,
                  "type": "integer"
                },
                "transactionId": {
                  "type": "string"
                }
              },
              "required": [
                "batchLogId",
                "transactionId",
                "occurredOn"
              ],
              "type": "object"
            },
            "type": "array"
          },
          "outboxPending": {
            "description": "C3 status pushes not yet delivered",
            "type": "integer"
          },
          "sources": {
            "items": {
              "additionalProperties": false,
              "properties": {
                "approved": {
                  "type": "integer"
                },
                "claimMode": {
                  "description": "立替の正とする連携 (J11)",
                  "enum": [
                    "claim",
                    "detail_only"
                  ],
                  "type": "string"
                },
                "configured": {
                  "type": "boolean"
                },
                "cursor": {
                  "nullable": true,
                  "type": "string"
                },
                "drafted": {
                  "type": "integer"
                },
                "enabled": {
                  "type": "boolean"
                },
                "endpoint": {
                  "nullable": true,
                  "type": "string"
                },
                "failed": {
                  "type": "integer"
                },
                "hasToken": {
                  "type": "boolean"
                },
                "lagMinutes": {
                  "description": "Minutes since the last successful pull",
                  "nullable": true,
                  "type": "integer"
                },
                "lastError": {
                  "nullable": true,
                  "type": "string"
                },
                "lastPulledAt": {
                  "format": "date-time",
                  "nullable": true,
                  "type": "string"
                },
                "source": {
                  "enum": [
                    "tsumagoi",
                    "yen_yen",
                    "stripe"
                  ],
                  "type": "string"
                }
              },
              "required": [
                "source",
                "configured",
                "enabled",
                "endpoint",
                "hasToken",
                "cursor",
                "lastPulledAt",
                "lagMinutes",
                "lastError",
                "claimMode",
                "drafted",
                "failed",
                "approved"
              ],
              "type": "object"
            },
            "type": "array"
          },
          "unmatchedPayouts": {
            "additionalProperties": false,
            "properties": {
              "count": {
                "type": "integer"
              },
              "items": {
                "items": {
                  "additionalProperties": false,
                  "properties": {
                    "ageDays": {
                      "type": "integer"
                    },
                    "arrivalDate": {
                      "type": "integer"
                    },
                    "batchLogId": {
                      "format": "uuid",
                      "type": "string"
                    },
                    "net": {
                      "type": "number"
                    },
                    "payoutId": {
                      "type": "string"
                    },
                    "provider": {
                      "enum": [
                        "paypay",
                        "square",
                        "stripe"
                      ],
                      "type": "string"
                    },
                    "source": {
                      "enum": [
                        "tsumagoi",
                        "yen_yen",
                        "stripe"
                      ],
                      "type": "string"
                    },
                    "status": {
                      "enum": [
                        "drafted",
                        "approved",
                        "skipped",
                        "failed",
                        "superseded"
                      ],
                      "type": "string"
                    }
                  },
                  "required": [
                    "batchLogId",
                    "source",
                    "provider",
                    "payoutId",
                    "net",
                    "arrivalDate",
                    "ageDays",
                    "status"
                  ],
                  "type": "object"
                },
                "type": "array"
              },
              "oldestAgeDays": {
                "nullable": true,
                "type": "integer"
              }
            },
            "required": [
              "count",
              "oldestAgeDays",
              "items"
            ],
            "type": "object"
          }
        },
        "required": [
          "sources",
          "draftsAwaitingApproval",
          "failedBatches",
          "unmatchedPayouts",
          "lateReceipts",
          "outboxPending"
        ],
        "type": "object"
      },
      "IntegrityCheckHistoryResponse": {
        "properties": {
          "data": {
            "properties": {
              "items": {
                "items": {
                  "$ref": "#/components/schemas/IntegrityCheckRun"
                },
                "type": "array"
              },
              "pagination": {
                "properties": {
                  "hasNext": {
                    "example": true,
                    "type": "boolean"
                  },
                  "hasPrevious": {
                    "example": false,
                    "type": "boolean"
                  },
                  "page": {
                    "example": 1,
                    "type": "integer"
                  },
                  "pageSize": {
                    "example": 20,
                    "type": "integer"
                  },
                  "totalItems": {
                    "example": 45,
                    "type": "integer"
                  },
                  "totalPages": {
                    "example": 3,
                    "type": "integer"
                  }
                },
                "type": "object"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "整合性チェック履歴を取得しました",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "IntegrityCheckResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/IntegrityCheckRun"
          },
          "message": {
            "example": "データ整合性の問題が検出されました",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "IntegrityCheckRun": {
        "properties": {
          "bankToJournalRate": {
            "description": "Bank to journal reconciliation rate",
            "example": 0.95,
            "format": "double",
            "nullable": true,
            "type": "number"
          },
          "checkType": {
            "$ref": "#/components/schemas/IntegrityCheckType"
          },
          "completedAt": {
            "description": "Check completion timestamp",
            "example": "2024-03-15T10:30:02.500Z",
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "executionTimeMs": {
            "description": "Check execution time in milliseconds",
            "example": 2500,
            "type": "integer"
          },
          "fiscalYear": {
            "description": "Fiscal year period",
            "example": "2025/02/16-2026/02/15",
            "nullable": true,
            "type": "string"
          },
          "id": {
            "description": "Check run ID",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "isValid": {
            "description": "Whether all checks passed",
            "example": false,
            "type": "boolean"
          },
          "overallIntegrityRate": {
            "description": "Overall data integrity rate",
            "example": 0.92,
            "format": "double",
            "nullable": true,
            "type": "number"
          },
          "periodEnd": {
            "description": "End date in YYYYMMDD format",
            "example": 20240930,
            "nullable": true,
            "type": "integer"
          },
          "periodStart": {
            "description": "Start date in YYYYMMDD format",
            "example": 20240401,
            "nullable": true,
            "type": "integer"
          },
          "startedAt": {
            "description": "Check start timestamp",
            "example": "2024-03-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "summary": {
            "$ref": "#/components/schemas/CheckSummary"
          },
          "userId": {
            "description": "User who initiated the check",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "violationCount": {
            "description": "Total number of violations detected",
            "example": 3,
            "type": "integer"
          },
          "violations": {
            "description": "List of detected violations",
            "items": {
              "$ref": "#/components/schemas/IntegrityViolation"
            },
            "type": "array"
          }
        },
        "required": [
          "id",
          "userId",
          "checkType",
          "isValid",
          "summary",
          "violationCount",
          "executionTimeMs",
          "startedAt"
        ],
        "type": "object"
      },
      "IntegrityCheckType": {
        "description": "Type of integrity check to perform",
        "enum": [
          "comprehensive",
          "bank_only",
          "journal_only",
          "period_close"
        ],
        "example": "comprehensive",
        "type": "string"
      },
      "IntegrityViolation": {
        "properties": {
          "affectedEntityId": {
            "description": "ID of affected entity (transaction, journal entry, etc.)",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "affectedEntityType": {
            "description": "Type of affected entity",
            "example": "bank_transaction",
            "type": "string"
          },
          "checkRunId": {
            "description": "Associated check run ID",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "createdAt": {
            "description": "Violation creation timestamp",
            "example": "2024-03-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "description": {
            "description": "Detailed violation description",
            "example": "重複する銀行取引が検出されました: 同一金額・同一日付",
            "type": "string"
          },
          "id": {
            "description": "Violation ID",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "ignoredReason": {
            "description": "Reason for ignoring violation",
            "example": "システム移行時の一時的な重複",
            "nullable": true,
            "type": "string"
          },
          "resolutionNotes": {
            "description": "Resolution notes",
            "example": "重複取引を削除しました",
            "nullable": true,
            "type": "string"
          },
          "severity": {
            "$ref": "#/components/schemas/ViolationSeverity"
          },
          "status": {
            "$ref": "#/components/schemas/ViolationStatus"
          },
          "updatedAt": {
            "description": "Last update timestamp",
            "example": "2024-03-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "violationType": {
            "$ref": "#/components/schemas/ViolationType"
          }
        },
        "required": [
          "id",
          "checkRunId",
          "violationType",
          "severity",
          "status",
          "description",
          "createdAt",
          "updatedAt"
        ],
        "type": "object"
      },
      "InterestIncomeCalculation": {
        "description": "Interest income calculation details for bank interest (受取利息). Includes withholding tax calculation for corporations (15.315%).",
        "properties": {
          "accountCodes": {
            "description": "Account codes used for the 3-line journal entry",
            "properties": {
              "bankAccount": {
                "description": "Bank account code (default: 102 for 普通預金)",
                "example": "102",
                "type": "string"
              },
              "interestIncome": {
                "description": "Interest income code (403 for 受取利息)",
                "example": "403",
                "type": "string"
              },
              "prepaidTax": {
                "description": "Prepaid corporate tax code (137 for 仮払法人税等)",
                "example": "137",
                "type": "string"
              }
            },
            "type": "object"
          },
          "entityType": {
            "description": "Entity type used for calculation",
            "enum": [
              "corporate",
              "individual"
            ],
            "example": "corporate",
            "type": "string"
          },
          "grossAmount": {
            "description": "Gross amount before withholding (税引前総額 = 受取利息 account)",
            "example": 483,
            "type": "number"
          },
          "isInterestIncome": {
            "description": "Whether this transaction was detected as interest income",
            "example": true,
            "type": "boolean"
          },
          "netAmount": {
            "description": "Net amount actually received (手取り額 = the deposit amount)",
            "example": 409,
            "type": "number"
          },
          "withholdingRate": {
            "description": "Withholding tax rate applied (0.15315 for corporations)",
            "example": 0.15315,
            "type": "number"
          },
          "withholdingTax": {
            "description": "Withholding tax amount (源泉徴収税 = 仮払法人税等 account)",
            "example": 74,
            "type": "number"
          }
        },
        "type": "object"
      },
      "InterimComparison": {
        "description": "中間申告: 予定申告 (前期実績) vs 仮決算 (the first six months priced from the books). Tested per group: 法人税・地方法人税・法人税割 under 法人税法72条1項ただし書, 事業税・特別法人事業税 under 地方税法72条の26第1項ただし書.",
        "properties": {
          "bestTotalYen": {
            "type": "integer"
          },
          "books": {
            "properties": {
              "endDate": {
                "format": "date",
                "type": "string"
              },
              "expensesYen": {
                "type": "integer"
              },
              "incomeBeforeTaxYen": {
                "type": "integer"
              },
              "recordCount": {
                "type": "integer"
              },
              "revenueYen": {
                "type": "integer"
              },
              "startDate": {
                "format": "date",
                "type": "string"
              }
            },
            "required": [
              "startDate",
              "endDate",
              "revenueYen",
              "expensesYen",
              "incomeBeforeTaxYen",
              "recordCount"
            ],
            "type": "object"
          },
          "caveats": {
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "dueDate": {
            "format": "date",
            "type": "string"
          },
          "groups": {
            "items": {
              "properties": {
                "allowed": {
                  "type": "boolean"
                },
                "chosen": {
                  "enum": [
                    "yotei",
                    "karikessan"
                  ],
                  "type": "string"
                },
                "group": {
                  "enum": [
                    "national",
                    "enterprise"
                  ],
                  "type": "string"
                },
                "karikessanYen": {
                  "nullable": true,
                  "type": "integer"
                },
                "label": {
                  "type": "string"
                },
                "reason": {
                  "type": "string"
                },
                "yoteiYen": {
                  "nullable": true,
                  "type": "integer"
                }
              },
              "required": [
                "group",
                "label",
                "allowed",
                "reason",
                "yoteiYen",
                "karikessanYen",
                "chosen"
              ],
              "type": "object"
            },
            "type": "array"
          },
          "halfPeriod": {
            "properties": {
              "endDate": {
                "format": "date",
                "type": "string"
              },
              "months": {
                "enum": [
                  6
                ],
                "type": "integer"
              },
              "startDate": {
                "format": "date",
                "type": "string"
              }
            },
            "required": [
              "startDate",
              "endDate",
              "months"
            ],
            "type": "object"
          },
          "headline": {
            "type": "string"
          },
          "lines": {
            "items": {
              "properties": {
                "chosen": {
                  "enum": [
                    "yotei",
                    "karikessan"
                  ],
                  "type": "string"
                },
                "karikessanYen": {
                  "type": "integer"
                },
                "key": {
                  "enum": [
                    "corporate_tax",
                    "chihou_hojinzei",
                    "hojinzeiwari",
                    "jigyo_zei",
                    "tokubetsu_hojin_jigyo_zei",
                    "kintouwari"
                  ],
                  "type": "string"
                },
                "label": {
                  "type": "string"
                },
                "payee": {
                  "enum": [
                    "national",
                    "local"
                  ],
                  "type": "string"
                },
                "yoteiYen": {
                  "nullable": true,
                  "type": "integer"
                }
              },
              "required": [
                "key",
                "label",
                "payee",
                "yoteiYen",
                "karikessanYen",
                "chosen"
              ],
              "type": "object"
            },
            "type": "array"
          },
          "requirements": {
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "savingsYen": {
            "type": "integer"
          },
          "sources": {
            "items": {
              "$ref": "#/components/schemas/GuidanceSource"
            },
            "type": "array"
          },
          "status": {
            "enum": [
              "not_required",
              "karikessan_saves",
              "yotei_cheaper",
              "about_the_same",
              "karikessan_not_allowed"
            ],
            "type": "string"
          },
          "taxableIncome": {
            "properties": {
              "incomeBeforeTaxYen": {
                "type": "integer"
              },
              "lines": {
                "items": {
                  "properties": {
                    "key": {
                      "enum": [
                        "entertainment",
                        "inhabitant_tax",
                        "loss_carryforward"
                      ],
                      "type": "string"
                    },
                    "label": {
                      "type": "string"
                    },
                    "yen": {
                      "type": "integer"
                    }
                  },
                  "required": [
                    "key",
                    "label",
                    "yen"
                  ],
                  "type": "object"
                },
                "type": "array"
              },
              "taxableIncomeYen": {
                "description": "Signed: negative is the half’s 欠損金額",
                "type": "integer"
              }
            },
            "required": [
              "incomeBeforeTaxYen",
              "lines",
              "taxableIncomeYen"
            ],
            "type": "object"
          },
          "yotei": {
            "properties": {
              "fromNotice": {
                "properties": {
                  "local": {
                    "type": "boolean"
                  },
                  "national": {
                    "type": "boolean"
                  }
                },
                "required": [
                  "national",
                  "local"
                ],
                "type": "object"
              },
              "localYen": {
                "nullable": true,
                "type": "integer"
              },
              "nationalYen": {
                "type": "integer"
              },
              "priorCorporateTaxYen": {
                "nullable": true,
                "type": "integer"
              },
              "priorPeriodMonths": {
                "type": "integer"
              },
              "totalYen": {
                "type": "integer"
              }
            },
            "required": [
              "priorCorporateTaxYen",
              "priorPeriodMonths",
              "nationalYen",
              "localYen",
              "totalYen",
              "fromNotice"
            ],
            "type": "object"
          }
        },
        "required": [
          "status",
          "headline",
          "dueDate",
          "halfPeriod",
          "yotei",
          "books",
          "taxableIncome",
          "groups",
          "lines",
          "bestTotalYen",
          "savingsYen",
          "requirements",
          "caveats",
          "sources"
        ],
        "type": "object"
      },
      "InventoryCategory": {
        "description": "J-GAAP inventory category (6 types)",
        "enum": [
          "product",
          "manufactured",
          "semi_manufactured",
          "work_in_progress",
          "raw_material",
          "stored_supply"
        ],
        "type": "string"
      },
      "InventoryItem": {
        "properties": {
          "category": {
            "$ref": "#/components/schemas/InventoryCategory"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "itemClass": {
            "$ref": "#/components/schemas/InventoryItemClass"
          },
          "name": {
            "type": "string"
          },
          "quantity": {
            "type": "number"
          },
          "unit": {
            "type": "string"
          },
          "unitCostJpy": {
            "description": "Integer JPY",
            "type": "integer"
          },
          "valuationMethod": {
            "type": "string"
          }
        },
        "type": "object"
      },
      "InventoryItemClass": {
        "description": "inventory_asset = valued on B/S; tracked_supply = audit register only",
        "enum": [
          "inventory_asset",
          "tracked_supply"
        ],
        "type": "string"
      },
      "InvoiceItem": {
        "properties": {
          "amount": {
            "description": "Total amount (quantity × unitPrice)",
            "example": 200000,
            "minimum": 0,
            "type": "number"
          },
          "detail": {
            "description": "Item details or specifications",
            "example": "Frontend development using React.js",
            "nullable": true,
            "type": "string"
          },
          "id": {
            "description": "Item identifier",
            "example": "item_123",
            "type": "string"
          },
          "item": {
            "description": "Item name or description",
            "example": "Web Development Services",
            "type": "string"
          },
          "quantity": {
            "description": "Quantity as string (supports various formats)",
            "example": "40 hours",
            "type": "string"
          },
          "unitPrice": {
            "description": "Price per unit",
            "example": 5000,
            "minimum": 0,
            "type": "number"
          }
        },
        "required": [
          "id",
          "item",
          "quantity",
          "unitPrice",
          "amount"
        ],
        "type": "object"
      },
      "InvoiceVerificationDetail": {
        "properties": {
          "company_name": {
            "example": "株式会社サンプル",
            "type": "string"
          },
          "is_valid": {
            "example": true,
            "type": "boolean"
          },
          "registration_date": {
            "example": "2023-10-01",
            "format": "date",
            "type": "string"
          },
          "registration_number": {
            "example": "T1234567890123",
            "type": "string"
          },
          "status": {
            "example": "active",
            "type": "string"
          },
          "verification_date": {
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          }
        },
        "type": "object"
      },
      "InvoiceVerificationOnDateRequest": {
        "properties": {
          "date": {
            "description": "Date to check verification status (YYYY-MM-DD)",
            "example": "2024-01-15",
            "format": "date",
            "type": "string"
          },
          "registration_number": {
            "description": "Invoice registration number to verify",
            "example": "T1234567890123",
            "pattern": "^T\\d{13}$",
            "type": "string"
          }
        },
        "required": [
          "registration_number",
          "date"
        ],
        "type": "object"
      },
      "InvoiceVerificationRequest": {
        "properties": {
          "include_history": {
            "default": false,
            "description": "Include historical verification data",
            "example": false,
            "type": "boolean"
          },
          "registration_number": {
            "description": "Invoice registration number to verify",
            "example": "T1234567890123",
            "pattern": "^T\\d{13}$",
            "type": "string"
          }
        },
        "required": [
          "registration_number"
        ],
        "type": "object"
      },
      "InvoiceVerificationResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/InvoiceVerificationDetail"
          },
          "message": {
            "example": "Invoice verification completed",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "type": "object"
      },
      "IssueCode": {
        "description": "機械可読な指摘種別識別子。エンジン横断でユニーク。",
        "enum": [
          "compliance-issues",
          "risk-summary",
          "evidence-coverage",
          "ledger-integrity",
          "forgotten-invoice",
          "dedup",
          "account-classification",
          "books-advisor",
          "integrity-check",
          "bad-invoice",
          "bad-journaling",
          "dangerous-claim",
          "duplicate-claim",
          "DUPLICATE_TRANSACTION",
          "AMOUNT_MISMATCH",
          "DATE_MISMATCH",
          "ACCOUNT_MISMATCH",
          "MISSING_LINK",
          "BALANCE_ERROR",
          "COUNT_MISMATCH",
          "MISSING_EVIDENCE",
          "PERIOD_BOUNDARY",
          "TAX_CALCULATION",
          "SUSPENSE_BALANCE",
          "UNPAID_INVOICE",
          "FRACTIONAL_JPY",
          "EXPENSE_JOURNAL_MISMATCH",
          "ORPHANED_PUBLISHED_DOCUMENT",
          "ORPHAN_JOURNAL_ENTRY",
          "BALANCE_CHAIN_BREAK",
          "JOURNAL_LINE_TOTAL_MISMATCH",
          "JEL_GLL_MISMATCH",
          "DUPLICATE_ACCOUNT",
          "MISSING_TAX_PROVISION",
          "CARRY_FORWARD_FAILED",
          "TAX_DECLARATION_MISMATCH",
          "CONSUMPTION_TAX_CLASSIFICATION",
          "TAX_PROVISION_UNSETTLED",
          "CONSUMPTION_TAX_DECLARATION_MISMATCH",
          "IN_SERVICE_EQUALS_PAYMENT_DATE",
          "CAPITAL_EXPENDITURE_SUSPECT",
          "PREPAID_INPUT_CREDIT",
          "TAX_CODE_ACCOUNT_MISMATCH",
          "OFFICER_COMP_NON_CONSTANT",
          "BEPPYO_RECONCILIATION_BREAK",
          "DEPOSIT_COMPONENT_IN_EXPENSE",
          "OFFICER_LOAN_DRIFT",
          "INVOICE_BANK_DOUBLE_COUNT",
          "SHATAKU_RENT_SHORTFALL",
          "TAXABLE_SALES_RATIO_WATCH",
          "INVOICE_MISSING_TRANSITIONAL",
          "KINTOWARI_MONTHS_MISMATCH",
          "OVERSEAS_WITHHOLDING_UNRECORDED",
          "FILED_BASELINE_DRIFT",
          "STAMPED_BUT_LIVE",
          "FIXED_ASSET_REGISTER_MISMATCH",
          "DUPLICATE_SPEND_CANDIDATE",
          "CLAIM_PERIOD_SLIP",
          "TAX_INCLUSIVE_SUSPENSE_BALANCE",
          "AMENDMENT_BASE_MISMATCH",
          "DOCUMENT_LINK_DANGLING",
          "EXPECTED_TAXABLE_TAGGED_OUTSIDE_SCOPE",
          "PAYROLL_SOCIAL_INSURANCE_VS_NOTICE",
          "WITHHOLDING_LIABILITY_RESIDUAL",
          "OFFICER_COMP_TOTAL_VS_PAY_COUNT",
          "CLAIM_JOURNAL_DRIFT",
          "unreconciled_transactions",
          "missing_evidence",
          "suspense_balance",
          "unpaid_invoices",
          "bank_balance_mismatch",
          "pending_expense_reports",
          "unreconciled_card",
          "duplicate_transactions",
          "month_end",
          "solvency",
          "capitalization",
          "depreciation",
          "compensation",
          "liquidity",
          "financing",
          "tax",
          "deferred_assets",
          "data_quality",
          "integrity"
        ],
        "example": "MISSING_EVIDENCE",
        "type": "string"
      },
      "IssueSeverity": {
        "description": "Severity level of accounting issue",
        "enum": [
          "error",
          "warning"
        ],
        "example": "warning",
        "type": "string"
      },
      "IssueType": {
        "description": "Type of accounting issue detected",
        "enum": [
          "UNBALANCED",
          "ORPHAN_ENTRY",
          "NEGATIVE_DEBIT_ACCOUNT",
          "NEGATIVE_CREDIT_ACCOUNT",
          "POTENTIAL_DUPLICATE"
        ],
        "example": "POTENTIAL_DUPLICATE",
        "type": "string"
      },
      "JPYIntegerComplianceInfo": {
        "description": "JPY integer compliance enforcement. 61 CHECK constraints across 16+ tables enforce floor(amount) = amount.",
        "properties": {
          "enforcement_layers": {
            "example": [
              "API Schema: @IsInt() on all monetary DTO fields",
              "Application: Math.round() on all calculations",
              "Database: 61 CHECK constraints (amount = FLOOR(amount))",
              "Nightly Cron: FRACTIONAL_JPY violation detection"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "protected_tables": {
            "example": [
              "bank_statements",
              "documents",
              "expenses",
              "general_ledger_lines",
              "journal_entries",
              "journal_entry_lines",
              "invoice_payments",
              "pay_slips",
              "pay_slip_items",
              "payment_statements",
              "reconciliation_links",
              "sales_invoice",
              "sales_invoice_item",
              "withholding_taxes",
              "recurring_patterns",
              "journal_templates",
              "simulation_transactions",
              "employees"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "total_check_constraints": {
            "description": "Total floor() CHECK constraints on monetary columns",
            "example": 61,
            "type": "integer"
          }
        },
        "type": "object"
      },
      "JobCancellationResponse": {
        "properties": {
          "data": {
            "example": "Job cancelled successfully",
            "type": "string"
          },
          "message": {
            "example": "Job cancelled successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "JobExecutionResult": {
        "properties": {
          "endTime": {
            "description": "Job completion timestamp",
            "example": "2024-01-15T04:00:02.500Z",
            "format": "date-time",
            "type": "string"
          },
          "errors": {
            "description": "Any errors encountered during execution",
            "example": [],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "executionTime": {
            "description": "Job execution time in milliseconds",
            "example": 2500,
            "minimum": 0,
            "type": "integer"
          },
          "jobName": {
            "description": "Name of the executed job",
            "example": "exchange-rate",
            "type": "string"
          },
          "result": {
            "description": "Job-specific execution results",
            "example": {
              "currenciesProcessed": [
                "USD",
                "EUR",
                "GBP"
              ],
              "errors": [],
              "ratesUpdated": 15
            },
            "type": "object"
          },
          "startTime": {
            "description": "Job start timestamp",
            "example": "2024-01-15T04:00:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "success": {
            "description": "Whether job execution was successful",
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "jobName",
          "success",
          "executionTime",
          "startTime",
          "endTime",
          "result",
          "errors"
        ],
        "type": "object"
      },
      "JobResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/QueueJob"
          },
          "message": {
            "example": "Job retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "JobResultResponse": {
        "properties": {
          "data": {
            "additionalProperties": true,
            "description": "Job result data (varies by job type)",
            "example": {
              "documentContent": "Processed document text...",
              "metadata": {
                "pages": 5,
                "wordCount": 1250
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Job result retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "JobStatus": {
        "properties": {
          "completedAt": {
            "description": "Completion timestamp (if completed)",
            "example": "2024-01-15T10:30:15.000Z",
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "jobId": {
            "description": "Job identifier",
            "example": "job_1640995200000_abc123def",
            "type": "string"
          },
          "result": {
            "additionalProperties": true,
            "description": "Job result data (if completed)",
            "example": {
              "documentContent": "Processed document text..."
            },
            "nullable": true,
            "type": "object"
          },
          "status": {
            "description": "Current job status",
            "enum": [
              "pending",
              "processing",
              "completed",
              "failed",
              "retrying",
              "cancelled"
            ],
            "example": "completed",
            "type": "string"
          }
        },
        "required": [
          "jobId",
          "status"
        ],
        "type": "object"
      },
      "JobStatusResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/JobStatus"
          },
          "message": {
            "example": "Job status retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "JobTriggerResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/JobExecutionResult"
          },
          "message": {
            "example": "Job executed successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "JobsListResponse": {
        "properties": {
          "data": {
            "properties": {
              "jobs": {
                "items": {
                  "$ref": "#/components/schemas/QueueJob"
                },
                "type": "array"
              },
              "pagination": {
                "properties": {
                  "hasMore": {
                    "example": true,
                    "type": "boolean"
                  },
                  "limit": {
                    "example": 50,
                    "type": "number"
                  },
                  "offset": {
                    "example": 0,
                    "type": "number"
                  },
                  "total": {
                    "example": 150,
                    "type": "number"
                  }
                },
                "required": [
                  "total",
                  "limit",
                  "offset",
                  "hasMore"
                ],
                "type": "object"
              }
            },
            "required": [
              "jobs",
              "pagination"
            ],
            "type": "object"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "JournalAuditLog": {
        "allOf": [
          {
            "$ref": "#/components/schemas/AuditLogEntry"
          },
          {
            "properties": {
              "journal_entry_id": {
                "description": "Referenced journal entry ID",
                "format": "uuid",
                "type": "string"
              }
            },
            "required": [
              "journal_entry_id"
            ],
            "type": "object"
          }
        ],
        "description": "Audit log for journal_entries table. Triggers: INSERT, UPDATE, DELETE."
      },
      "JournalContextPreset": {
        "properties": {
          "context": {
            "description": "Context text to be used in AI analysis",
            "example": "この取引は軽井沢別荘の管理運営に関連しています",
            "type": "string"
          },
          "createdAt": {
            "description": "Timestamp when the preset was created",
            "example": "2026-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "id": {
            "description": "Unique identifier for the preset",
            "example": "preset-1",
            "type": "string"
          },
          "label": {
            "description": "Display label for the preset (Japanese)",
            "example": "不動産管理",
            "type": "string"
          },
          "updatedAt": {
            "description": "Timestamp when the preset was last updated",
            "example": "2026-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          }
        },
        "required": [
          "id",
          "label",
          "context"
        ],
        "type": "object"
      },
      "JournalContextPresetsResponse": {
        "properties": {
          "data": {
            "items": {
              "$ref": "#/components/schemas/JournalContextPreset"
            },
            "type": "array"
          },
          "message": {
            "example": "Journal context presets retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "JournalEntry": {
        "properties": {
          "amount": {
            "description": "Transaction amount",
            "example": 5000,
            "type": "number"
          },
          "created_at": {
            "description": "Creation timestamp",
            "example": "2024-03-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "description": {
            "description": "Journal entry description",
            "example": "東京駅→大阪駅 新幹線代",
            "type": "string"
          },
          "entry_date": {
            "description": "Entry date in YYYYMMDD format",
            "example": 20251205,
            "type": "integer"
          },
          "id": {
            "description": "Journal entry ID",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "status": {
            "description": "Entry status",
            "example": "draft",
            "type": "string"
          }
        },
        "required": [
          "id",
          "entry_date",
          "description",
          "amount",
          "status",
          "created_at"
        ],
        "type": "object"
      },
      "JournalEntryCreateResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/JournalEntry"
          },
          "message": {
            "example": "Journal entry created from template successfully",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "JournalEntryLine": {
        "properties": {
          "account_code": {
            "description": "Account code for reference",
            "example": "4001",
            "type": "string"
          },
          "account_id": {
            "description": "Account identifier for this journal line",
            "example": "456e7890-f12a-34b5-c678-901234567890",
            "format": "uuid",
            "type": "string"
          },
          "account_name": {
            "description": "Account name in Japanese",
            "example": "売上高",
            "type": "string"
          },
          "credit_amount": {
            "description": "Credit amount (貸方金額)",
            "example": 0,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "debit_amount": {
            "description": "Debit amount (借方金額)",
            "example": 110000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "description": {
            "description": "Line item description",
            "example": "商品売上 - 株式会社ABC",
            "type": "string"
          },
          "entry_date": {
            "description": "The line's own date (YYYYMMDD); `entryDate` in the response. With the header date and the 課税仕入れの日 it is one of the dates the je_link period guard checks (BE ADR-0008).",
            "example": 20260528,
            "nullable": true,
            "type": "integer"
          },
          "id": {
            "description": "Journal entry line unique identifier",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "taxable_purchase_date": {
            "description": "The 課税仕入れの日 set on the line (YYYYMMDD), or null when the line date stands; `taxablePurchaseDate` in the response. Checked by the je_link period guard (BE ADR-0008).",
            "example": 20260520,
            "nullable": true,
            "type": "integer"
          }
        },
        "required": [
          "id",
          "account_id",
          "account_code",
          "account_name",
          "debit_amount",
          "credit_amount"
        ],
        "type": "object"
      },
      "JournalEntryResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/JournalEntry"
          },
          "message": {
            "example": "Journal entry retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "JournalEntryStatus": {
        "description": "Journal entry status in accounting workflow",
        "enum": [
          "draft",
          "posted",
          "reversed"
        ],
        "example": "posted",
        "type": "string"
      },
      "JournalEntryValidation": {
        "description": "Validation results for journal entries (v4.29). Enforces Japanese double-entry bookkeeping rules.",
        "properties": {
          "checks": {
            "description": "Detailed validation check results",
            "properties": {
              "allAmountsPositive": {
                "description": "Whether all amounts are positive integers",
                "example": true,
                "type": "boolean"
              },
              "bankAccountCorrectSide": {
                "description": "Whether bank account is on correct side (入金=借方, 出金=貸方)",
                "example": true,
                "type": "boolean"
              },
              "debitCreditBalance": {
                "description": "Whether debit total equals credit total (±1円許容)",
                "example": true,
                "type": "boolean"
              },
              "hasRequiredFields": {
                "description": "Whether all required fields are present",
                "example": true,
                "type": "boolean"
              },
              "notBothSidesBankOnly": {
                "description": "Whether both sides are NOT only bank accounts (except transfers)",
                "example": true,
                "type": "boolean"
              }
            },
            "required": [
              "debitCreditBalance",
              "bankAccountCorrectSide",
              "notBothSidesBankOnly",
              "allAmountsPositive",
              "hasRequiredFields"
            ],
            "type": "object"
          },
          "errors": {
            "description": "List of validation errors in Japanese (仕訳ルール違反)",
            "example": [
              "入金取引では借方に普通預金（または現金）が必要です"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "isValid": {
            "description": "Overall validation status - false if any rules violated",
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "isValid",
          "errors",
          "checks"
        ],
        "type": "object"
      },
      "JournalGenerationResponse": {
        "properties": {
          "data": {
            "properties": {
              "amount": {
                "description": "Journal entry amount",
                "example": 220000,
                "type": "number"
              },
              "invoiceId": {
                "description": "Source invoice identifier",
                "example": "123e4567-e89b-12d3-a456-426614174000",
                "format": "uuid",
                "type": "string"
              },
              "journalEntryId": {
                "description": "Generated journal entry identifier",
                "example": "789e0123-e45b-67c8-d901-234567890123",
                "format": "uuid",
                "type": "string"
              }
            },
            "required": [
              "journalEntryId",
              "invoiceId",
              "amount"
            ],
            "type": "object"
          },
          "message": {
            "example": "Journal entry generated successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "JournalLineageDiffResponse": {
        "properties": {
          "data": {
            "properties": {
              "hasSource": {
                "description": "False when no extracted document amount could be resolved for this entry",
                "example": true,
                "type": "boolean"
              },
              "hops": {
                "description": "Per-hop comparison between the source document value and the posted value",
                "items": {
                  "properties": {
                    "changed": {
                      "description": "True when |documentValue - journalValue| > 1 (¥1 tolerance)",
                      "example": false,
                      "type": "boolean"
                    },
                    "documentValue": {
                      "example": 152491,
                      "nullable": true,
                      "type": "number"
                    },
                    "field": {
                      "example": "amount",
                      "type": "string"
                    },
                    "journalValue": {
                      "example": 152491,
                      "nullable": true,
                      "type": "number"
                    },
                    "label": {
                      "example": "書類金額 → 仕訳金額",
                      "type": "string"
                    },
                    "source": {
                      "description": "Where the document value was resolved from",
                      "example": "expense_wizard_items.extracted_amount_jpy",
                      "type": "string"
                    }
                  },
                  "required": [
                    "field",
                    "label",
                    "documentValue",
                    "journalValue",
                    "changed",
                    "source"
                  ],
                  "type": "object"
                },
                "type": "array"
              },
              "journalEntryId": {
                "format": "uuid",
                "type": "string"
              }
            },
            "required": [
              "journalEntryId",
              "hasSource",
              "hops"
            ],
            "type": "object"
          },
          "message": {
            "example": "Journal lineage diff retrieved successfully",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "JournalListResponse": {
        "properties": {
          "data": {
            "properties": {
              "entries": {
                "items": {
                  "$ref": "#/components/schemas/JournalEntry"
                },
                "type": "array"
              },
              "pagination": {
                "properties": {
                  "page_number": {
                    "example": 1,
                    "type": "integer"
                  },
                  "page_size": {
                    "example": 20,
                    "type": "integer"
                  },
                  "total": {
                    "example": 245,
                    "type": "integer"
                  },
                  "total_pages": {
                    "example": 13,
                    "type": "integer"
                  }
                },
                "type": "object"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Journal entries retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "JournalPostingResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/JournalPostingResult"
          },
          "message": {
            "example": "Journal posted to ledger successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "JournalPostingResult": {
        "properties": {
          "accounts_affected": {
            "description": "Accounts affected by the journal posting",
            "items": {
              "properties": {
                "account_code": {
                  "description": "Account code",
                  "example": "1001",
                  "type": "string"
                },
                "account_id": {
                  "description": "Account identifier",
                  "example": "456e7890-f12a-34b5-c678-901234567890",
                  "format": "uuid",
                  "type": "string"
                },
                "account_name": {
                  "description": "Account name",
                  "example": "現金",
                  "type": "string"
                },
                "new_balance": {
                  "description": "New running balance after posting",
                  "example": 250000,
                  "format": "decimal",
                  "type": "number"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "entry_number": {
            "description": "Journal entry number",
            "example": "JE-2024-001",
            "type": "string"
          },
          "journal_entry_id": {
            "description": "Posted journal entry identifier",
            "example": "789e0123-e45b-67c8-d901-234567890123",
            "format": "uuid",
            "type": "string"
          },
          "ledger_lines_created": {
            "description": "Number of general ledger lines created",
            "example": 2,
            "minimum": 1,
            "type": "integer"
          },
          "posted_at": {
            "description": "Posting timestamp",
            "example": "2024-01-15T15:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "posted_by": {
            "description": "User who posted the journal entry",
            "example": "abc12345-def6-7890-ghij-klmnopqrstuv",
            "format": "uuid",
            "type": "string"
          },
          "status": {
            "description": "Updated journal entry status",
            "enum": [
              "posted"
            ],
            "example": "posted",
            "type": "string"
          },
          "total_amount": {
            "description": "Total transaction amount (debit = credit)",
            "example": 110000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          }
        },
        "required": [
          "journal_entry_id",
          "entry_number",
          "status",
          "posted_at",
          "posted_by",
          "ledger_lines_created",
          "total_amount",
          "accounts_affected"
        ],
        "type": "object"
      },
      "JournalReverseResponse": {
        "properties": {
          "data": {
            "properties": {
              "entryNumber": {
                "example": "RCL-2026-FUTSU1110",
                "type": "string"
              },
              "journalEntryId": {
                "format": "uuid",
                "type": "string"
              },
              "reversedLineCount": {
                "example": 2,
                "type": "integer"
              },
              "status": {
                "enum": [
                  "reversed"
                ],
                "type": "string"
              }
            },
            "required": [
              "journalEntryId",
              "entryNumber",
              "status",
              "reversedLineCount"
            ],
            "type": "object"
          },
          "message": {
            "example": "仕訳を取消しました",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "type": "object"
      },
      "JournalSide": {
        "description": "Journal entry side",
        "enum": [
          "debit",
          "credit"
        ],
        "example": "debit",
        "type": "string"
      },
      "JournalSourceType": {
        "description": "Source type indicating how the journal entry was created",
        "enum": [
          "manual",
          "expense_claim",
          "sales_invoice",
          "purchase_invoice",
          "bank_feed",
          "card_statement",
          "payroll",
          "fixed_asset",
          "depreciation",
          "opening_balance",
          "adjustment",
          "reversal"
        ],
        "example": "sales_invoice",
        "type": "string"
      },
      "JournalSummary": {
        "properties": {
          "entriesBySource": {
            "description": "Entry count breakdown by source type",
            "properties": {
              "expense_claim": {
                "example": 65,
                "type": "integer"
              },
              "manual": {
                "example": 45,
                "type": "integer"
              },
              "opening_balance": {
                "example": 15,
                "type": "integer"
              },
              "sales_invoice": {
                "example": 120,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "entriesByStatus": {
            "description": "Entry count breakdown by status",
            "properties": {
              "draft": {
                "example": 12,
                "type": "integer"
              },
              "posted": {
                "example": 230,
                "type": "integer"
              },
              "reversed": {
                "example": 3,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "totalCreditAmount": {
            "description": "Total credit amount across all entries",
            "example": 15750000,
            "format": "decimal",
            "type": "number"
          },
          "totalDebitAmount": {
            "description": "Total debit amount across all entries",
            "example": 15750000,
            "format": "decimal",
            "type": "number"
          },
          "totalEntries": {
            "description": "Total number of journal entries",
            "example": 245,
            "type": "integer"
          }
        },
        "required": [
          "totalEntries",
          "totalDebitAmount",
          "totalCreditAmount",
          "entriesByStatus",
          "entriesBySource"
        ],
        "type": "object"
      },
      "JournalSummaryResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/JournalSummary"
          },
          "message": {
            "example": "Journal summary retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "JournalTemplate": {
        "properties": {
          "accounts_journal_templates_credit_account_idToaccounts": {
            "$ref": "#/components/schemas/AccountInfo"
          },
          "accounts_journal_templates_debit_account_idToaccounts": {
            "$ref": "#/components/schemas/AccountInfo"
          },
          "created_at": {
            "description": "Creation timestamp",
            "example": "2024-03-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "credit_account_id": {
            "description": "Credit account ID",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "debit_account_id": {
            "description": "Debit account ID",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "default_amount": {
            "description": "Default amount",
            "example": 1000,
            "nullable": true,
            "type": "number"
          },
          "default_description": {
            "description": "Default journal entry description",
            "example": "交通費",
            "nullable": true,
            "type": "string"
          },
          "description": {
            "description": "Template description",
            "example": "電車・バス・タクシーなどの交通費",
            "nullable": true,
            "type": "string"
          },
          "id": {
            "description": "Template ID",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "is_active": {
            "description": "Whether template is active",
            "example": true,
            "type": "boolean"
          },
          "name": {
            "description": "Template name",
            "example": "交通費精算",
            "type": "string"
          },
          "shortcut_key": {
            "description": "Shortcut key (F1-F5)",
            "example": "F1",
            "nullable": true,
            "type": "string"
          },
          "tax_included": {
            "description": "Whether tax is included in amount",
            "example": false,
            "type": "boolean"
          },
          "tax_rate": {
            "$ref": "#/components/schemas/TaxRate"
          },
          "updated_at": {
            "description": "Last update timestamp",
            "example": "2024-03-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "usage_count": {
            "description": "Number of times template has been used",
            "example": 15,
            "type": "integer"
          },
          "user_id": {
            "description": "Owner user ID",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          }
        },
        "required": [
          "id",
          "user_id",
          "name",
          "debit_account_id",
          "credit_account_id",
          "tax_rate",
          "tax_included",
          "usage_count",
          "is_active",
          "created_at",
          "updated_at"
        ],
        "type": "object"
      },
      "JournalTemplateCreateResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/JournalTemplate"
          },
          "message": {
            "example": "Journal template created successfully",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "JournalTemplateDeleteResponse": {
        "properties": {
          "data": {
            "properties": {
              "success": {
                "example": true,
                "type": "boolean"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Journal template deleted successfully",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "JournalTemplateListResponse": {
        "properties": {
          "data": {
            "items": {
              "$ref": "#/components/schemas/JournalTemplate"
            },
            "type": "array"
          },
          "message": {
            "example": "Journal templates retrieved successfully",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "JournalTemplateResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/JournalTemplate"
          },
          "message": {
            "example": "Journal template retrieved successfully",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "JournalTemplateUpdateResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/JournalTemplate"
          },
          "message": {
            "example": "Journal template updated successfully",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "JournalType": {
        "description": "Journal entry type",
        "enum": [
          "reimbursement",
          "income",
          "expense",
          "transfer",
          "suspense"
        ],
        "example": "reimbursement",
        "type": "string"
      },
      "KPIDashboard": {
        "properties": {
          "alerts": {
            "description": "Business alerts and recommendations",
            "items": {
              "$ref": "#/components/schemas/EnhancedAlert"
            },
            "type": "array"
          },
          "generatedAt": {
            "description": "Report generation timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "historicalTrend": {
            "description": "Historical trend data for multi-year analysis",
            "items": {
              "properties": {
                "currentRatio": {
                  "format": "decimal",
                  "type": "number"
                },
                "grossMargin": {
                  "format": "decimal",
                  "type": "number"
                },
                "netMargin": {
                  "format": "decimal",
                  "type": "number"
                },
                "netProfit": {
                  "format": "decimal",
                  "type": "number"
                },
                "operatingMargin": {
                  "format": "decimal",
                  "type": "number"
                },
                "period": {
                  "example": "2024年度",
                  "type": "string"
                },
                "periodEnd": {
                  "example": 20241231,
                  "type": "integer"
                },
                "periodStart": {
                  "example": 20240101,
                  "type": "integer"
                },
                "totalRevenue": {
                  "format": "decimal",
                  "type": "number"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "periodEnd": {
            "$ref": "#/components/schemas/DateFormat"
          },
          "periodStart": {
            "$ref": "#/components/schemas/DateFormat"
          },
          "sections": {
            "properties": {
              "cashFlow": {
                "$ref": "#/components/schemas/KPISection"
              },
              "efficiency": {
                "$ref": "#/components/schemas/KPISection"
              },
              "growth": {
                "$ref": "#/components/schemas/KPISection"
              },
              "liquidity": {
                "$ref": "#/components/schemas/KPISection"
              },
              "profitability": {
                "$ref": "#/components/schemas/KPISection"
              }
            },
            "type": "object"
          }
        },
        "required": [
          "periodStart",
          "periodEnd",
          "sections",
          "alerts",
          "historicalTrend",
          "generatedAt"
        ],
        "type": "object"
      },
      "KPIMetric": {
        "properties": {
          "changePercent": {
            "description": "Percentage change from prior period",
            "example": 5.14,
            "format": "decimal",
            "nullable": true,
            "type": "number"
          },
          "name": {
            "description": "Metric name in English",
            "example": "Gross Profit Margin",
            "type": "string"
          },
          "nameJa": {
            "description": "Metric name in Japanese",
            "example": "売上総利益率",
            "type": "string"
          },
          "priorValue": {
            "description": "Prior period metric value",
            "example": 62.3,
            "format": "decimal",
            "nullable": true,
            "type": "number"
          },
          "status": {
            "$ref": "#/components/schemas/KPIStatus"
          },
          "threshold": {
            "nullable": true,
            "properties": {
              "good": {
                "format": "decimal",
                "type": "number"
              },
              "warning": {
                "format": "decimal",
                "type": "number"
              }
            },
            "type": "object"
          },
          "trend": {
            "$ref": "#/components/schemas/TrendDirection"
          },
          "unit": {
            "description": "Unit of measurement",
            "example": "%",
            "type": "string"
          },
          "value": {
            "description": "Current metric value",
            "example": 65.5,
            "format": "decimal",
            "type": "number"
          }
        },
        "required": [
          "name",
          "nameJa",
          "value",
          "unit",
          "status"
        ],
        "type": "object"
      },
      "KPISection": {
        "properties": {
          "metrics": {
            "description": "KPI metrics in this section",
            "items": {
              "$ref": "#/components/schemas/KPIMetric"
            },
            "type": "array"
          },
          "title": {
            "description": "Section title in English",
            "example": "Profitability Metrics",
            "type": "string"
          },
          "titleJa": {
            "description": "Section title in Japanese",
            "example": "収益性指標",
            "type": "string"
          }
        },
        "required": [
          "title",
          "titleJa",
          "metrics"
        ],
        "type": "object"
      },
      "KPIStatus": {
        "description": "KPI status based on threshold analysis",
        "enum": [
          "good",
          "warning",
          "critical"
        ],
        "example": "good",
        "type": "string"
      },
      "KnowledgeArticle": {
        "properties": {
          "category": {
            "example": "expense",
            "type": "string"
          },
          "content": {
            "description": "Full article content in Markdown",
            "type": "string"
          },
          "examples": {
            "items": {
              "properties": {
                "amount": {
                  "nullable": true,
                  "type": "number"
                },
                "scenario": {
                  "type": "string"
                },
                "solution": {
                  "type": "string"
                },
                "title": {
                  "type": "string"
                }
              },
              "type": "object"
            },
            "nullable": true,
            "type": "array"
          },
          "id": {
            "example": "kb_expense_consumables",
            "type": "string"
          },
          "lastUpdated": {
            "example": "2026-01-26",
            "type": "string"
          },
          "legalBasis": {
            "items": {
              "properties": {
                "law": {
                  "example": "Income Tax Act",
                  "type": "string"
                },
                "lawJa": {
                  "example": "所得税法",
                  "type": "string"
                },
                "section": {
                  "example": "Article 37",
                  "type": "string"
                },
                "sectionJa": {
                  "example": "第37条",
                  "type": "string"
                },
                "summary": {
                  "example": "必要経費に関する規定",
                  "type": "string"
                },
                "url": {
                  "nullable": true,
                  "type": "string"
                }
              },
              "type": "object"
            },
            "nullable": true,
            "type": "array"
          },
          "relatedTopics": {
            "example": [
              "固定資産",
              "少額減価償却資産"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "relevantScreens": {
            "example": [
              "expense_wizard",
              "document_upload",
              "journal_entry"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "subcategory": {
            "example": "office_supplies",
            "nullable": true,
            "type": "string"
          },
          "summary": {
            "example": "10万円未満の事務用品は全額経費として即時計上できます。",
            "type": "string"
          },
          "tags": {
            "example": [
              "消耗品",
              "事務用品",
              "経費",
              "10万円"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "title": {
            "example": "Office Supplies as Business Expense",
            "type": "string"
          },
          "titleJa": {
            "example": "消耗品費（事務用品）の経費計上",
            "type": "string"
          },
          "warnings": {
            "items": {
              "type": "string"
            },
            "nullable": true,
            "type": "array"
          }
        },
        "type": "object"
      },
      "KnowledgeCategory": {
        "properties": {
          "category": {
            "example": "expense",
            "type": "string"
          },
          "count": {
            "example": 5,
            "type": "integer"
          },
          "label": {
            "example": "経費",
            "type": "string"
          }
        },
        "type": "object"
      },
      "LayoutInitData": {
        "description": "Only the requested sections are present. Every section is computed independently and is `null` (or its documented empty value) when that read failed.",
        "properties": {
          "accountingSettings": {
            "additionalProperties": true,
            "description": "Journal posting mode and pending draft count.",
            "nullable": true,
            "properties": {
              "autoPostJournals": {
                "type": "boolean"
              },
              "description": {
                "type": "string"
              },
              "mode": {
                "enum": [
                  "auto",
                  "manual"
                ],
                "type": "string"
              },
              "pendingDraftsCount": {
                "example": 5,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "accounts": {
            "additionalProperties": true,
            "description": "Account list grouped by account type (勘定科目).",
            "nullable": true,
            "type": "object"
          },
          "advisorConversations": {
            "description": "The 5 most recent AI advisor conversations (`[]` when the read failed).",
            "items": {
              "additionalProperties": true,
              "type": "object"
            },
            "type": "array"
          },
          "aiSettings": {
            "allOf": [
              {
                "$ref": "#/components/schemas/AISettingsSchema"
              }
            ],
            "description": "Opt-in (`include=aiSettings`). Same data as `GET /api/user-profile/ai-settings` `data` (API keys masked). Never served from the layout cache.",
            "nullable": true
          },
          "bankConnections": {
            "description": "The caller's bank API connections (`[]` when the read failed).",
            "items": {
              "additionalProperties": true,
              "type": "object"
            },
            "type": "array"
          },
          "company": {
            "additionalProperties": true,
            "description": "The caller's company (same data as the company endpoints).",
            "nullable": true,
            "type": "object"
          },
          "disclaimer": {
            "allOf": [
              {
                "$ref": "#/components/schemas/AdvisorDisclaimerStatus"
              }
            ],
            "description": "Opt-in (`include=disclaimer`). Same data as `GET /api/advisor/disclaimer` `data`. Never served from the layout cache.",
            "nullable": true
          },
          "documentStatistics": {
            "additionalProperties": true,
            "description": "Document counts by type.",
            "nullable": true,
            "type": "object"
          },
          "establishment": {
            "additionalProperties": true,
            "description": "Establishment-guide progress.",
            "nullable": true,
            "type": "object"
          },
          "fiscalPeriods": {
            "description": "Opt-in (`include=fiscalPeriods`). The fiscal-period rows of `GET /api/tax/fiscal-periods`, newest first. Never served from the layout cache.",
            "items": {
              "$ref": "#/components/schemas/FiscalPeriod"
            },
            "nullable": true,
            "type": "array"
          },
          "gamification": {
            "additionalProperties": true,
            "description": "Gamification progress and achievements.",
            "nullable": true,
            "type": "object"
          },
          "gamificationDefinitions": {
            "additionalProperties": true,
            "description": "Static level / achievement / goal / XP definitions.",
            "nullable": true,
            "type": "object"
          },
          "holidays": {
            "additionalProperties": {
              "properties": {
                "holidays": {
                  "items": {
                    "properties": {
                      "date": {
                        "example": "2026-05-04",
                        "type": "string"
                      },
                      "name": {
                        "example": "みどりの日",
                        "type": "string"
                      },
                      "nameEn": {
                        "example": "Greenery Day",
                        "type": "string"
                      }
                    },
                    "type": "object"
                  },
                  "type": "array"
                },
                "year": {
                  "example": 2026,
                  "type": "integer"
                }
              },
              "type": "object"
            },
            "description": "Japanese national holidays for the current and the next year, keyed by year: `{ [year]: { year, holidays[] } }`.",
            "type": "object"
          },
          "insights": {
            "description": "Proactive-insight counters (`{ total: 0, unread: 0 }` when the read failed).",
            "properties": {
              "count": {
                "properties": {
                  "total": {
                    "example": 3,
                    "type": "integer"
                  },
                  "unread": {
                    "example": 1,
                    "type": "integer"
                  }
                },
                "type": "object"
              }
            },
            "type": "object"
          },
          "prefectures": {
            "description": "The 47 prefectures (static list).",
            "items": {
              "additionalProperties": true,
              "type": "object"
            },
            "nullable": true,
            "type": "array"
          },
          "preferences": {
            "additionalProperties": true,
            "description": "User preferences.",
            "nullable": true,
            "type": "object"
          },
          "reminders": {
            "description": "Reminder configs and custom reminders; each part is `null` when its read failed.",
            "properties": {
              "configs": {
                "items": {
                  "additionalProperties": true,
                  "type": "object"
                },
                "nullable": true,
                "type": "array"
              },
              "custom": {
                "items": {
                  "additionalProperties": true,
                  "type": "object"
                },
                "nullable": true,
                "type": "array"
              }
            },
            "type": "object"
          },
          "uiPreferences": {
            "allOf": [
              {
                "$ref": "#/components/schemas/UiPreferences"
              }
            ],
            "description": "Opt-in (`include=uiPreferences`). Same data as `GET /api/user-profile/ui-preferences` `data`. Never served from the layout cache.",
            "nullable": true
          }
        },
        "type": "object"
      },
      "LayoutInitResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/LayoutInitData"
          },
          "meta": {
            "properties": {
              "cached": {
                "description": "True when every requested section came from the per-user in-process cache (120 s).",
                "type": "boolean"
              },
              "durationMs": {
                "example": 180,
                "type": "integer"
              },
              "sections": {
                "description": "The requested section keys, lower-cased.",
                "items": {
                  "type": "string"
                },
                "type": "array"
              }
            },
            "type": "object"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data",
          "meta"
        ],
        "type": "object"
      },
      "LeaderboardResponse": {
        "properties": {
          "leaderboard": {
            "items": {
              "properties": {
                "avatar_url": {
                  "nullable": true,
                  "type": "string"
                },
                "level": {
                  "type": "integer"
                },
                "level_name": {
                  "properties": {
                    "en": {
                      "type": "string"
                    },
                    "ja": {
                      "type": "string"
                    }
                  },
                  "type": "object"
                },
                "rank": {
                  "type": "integer"
                },
                "user_id": {
                  "format": "uuid",
                  "type": "string"
                },
                "user_name": {
                  "nullable": true,
                  "type": "string"
                },
                "xp": {
                  "type": "integer"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "user_rank": {
            "nullable": true,
            "type": "integer"
          }
        },
        "type": "object"
      },
      "LedgerConnection": {
        "properties": {
          "created_at": {
            "format": "date-time",
            "type": "string"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "last_synced_at": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "provider": {
            "example": "freee",
            "type": "string"
          },
          "status": {
            "enum": [
              "active",
              "expired",
              "revoked",
              "error"
            ],
            "type": "string"
          }
        },
        "type": "object"
      },
      "LedgerSummaryPeriod": {
        "properties": {
          "accounts": {
            "description": "Account-wise ledger summaries",
            "items": {
              "$ref": "#/components/schemas/AccountLedgerSummary"
            },
            "type": "array"
          },
          "end_date": {
            "description": "Period end date in YYYYMMDD format",
            "example": 20241231,
            "maximum": 99991231,
            "minimum": 19000101,
            "type": "integer"
          },
          "start_date": {
            "description": "Period start date in YYYYMMDD format",
            "example": 20240401,
            "maximum": 99991231,
            "minimum": 19000101,
            "type": "integer"
          },
          "total_accounts": {
            "description": "Total number of accounts in summary",
            "example": 25,
            "minimum": 0,
            "type": "integer"
          },
          "total_credit_amount": {
            "description": "Total credit amount across all accounts",
            "example": 5750000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "total_debit_amount": {
            "description": "Total debit amount across all accounts",
            "example": 5750000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "total_transactions": {
            "description": "Total number of transactions in period",
            "example": 150,
            "minimum": 0,
            "type": "integer"
          }
        },
        "required": [
          "start_date",
          "end_date",
          "total_accounts",
          "total_transactions",
          "total_debit_amount",
          "total_credit_amount",
          "accounts"
        ],
        "type": "object"
      },
      "LedgerSummaryResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/LedgerSummaryPeriod"
          },
          "message": {
            "example": "Ledger summary retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "LevelDefinition": {
        "description": "Level definition with visual metadata (v4.70)",
        "properties": {
          "benefits": {
            "example": [
              "基本機能へのアクセス"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "color": {
            "description": "Semantic color identifier",
            "example": "gray",
            "type": "string"
          },
          "description": {
            "properties": {
              "en": {
                "example": "Your accounting journey begins",
                "type": "string"
              },
              "ja": {
                "example": "経理の旅が始まりました",
                "type": "string"
              }
            },
            "type": "object"
          },
          "iconName": {
            "description": "Icon identifier",
            "example": "Footprints",
            "type": "string"
          },
          "level": {
            "example": 1,
            "type": "integer"
          },
          "maxXP": {
            "description": "-1 for max level",
            "example": 100,
            "type": "integer"
          },
          "minXP": {
            "example": 0,
            "type": "integer"
          },
          "name": {
            "properties": {
              "en": {
                "example": "Accounting Newcomer",
                "type": "string"
              },
              "ja": {
                "example": "新人経理",
                "type": "string"
              }
            },
            "type": "object"
          },
          "tier": {
            "example": "beginner",
            "type": "string"
          }
        },
        "type": "object"
      },
      "LevelInfoResponse": {
        "description": "Enhanced level info included in progress response (v4.70)",
        "properties": {
          "color": {
            "description": "Semantic color identifier",
            "example": "gray",
            "type": "string"
          },
          "description": {
            "properties": {
              "en": {
                "example": "Your accounting journey begins",
                "type": "string"
              },
              "ja": {
                "example": "経理の旅が始まりました",
                "type": "string"
              }
            },
            "type": "object"
          },
          "iconName": {
            "description": "Icon identifier (e.g. Lucide icon name)",
            "example": "Footprints",
            "type": "string"
          },
          "maxXP": {
            "description": "-1 for max level (Infinity in JSON)",
            "example": 100,
            "type": "integer"
          },
          "minXP": {
            "example": 0,
            "type": "integer"
          },
          "name": {
            "properties": {
              "en": {
                "example": "Accounting Newcomer",
                "type": "string"
              },
              "ja": {
                "example": "新人経理",
                "type": "string"
              }
            },
            "type": "object"
          },
          "tier": {
            "example": "beginner",
            "type": "string"
          }
        },
        "type": "object"
      },
      "LineLinkStatus": {
        "additionalProperties": false,
        "properties": {
          "addFriendUrl": {
            "description": "The official account’s 友だち追加 link",
            "format": "uri",
            "nullable": true,
            "type": "string"
          },
          "configured": {
            "description": "false until the channel keys are set (the feature is dark)",
            "type": "boolean"
          },
          "linked": {
            "type": "boolean"
          },
          "linkedAt": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          }
        },
        "required": [
          "configured",
          "linked",
          "linkedAt",
          "addFriendUrl"
        ],
        "type": "object"
      },
      "LinkBankTransactionRequest": {
        "properties": {
          "bank_transaction_id": {
            "description": "Bank transaction ID to link",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          }
        },
        "required": [
          "bank_transaction_id"
        ],
        "type": "object"
      },
      "LinkClaimsToPaymentRequest": {
        "properties": {
          "claims_document_id": {
            "description": "Claims document ID to link",
            "example": "456e7890-f12a-34b5-c678-901234567890",
            "format": "uuid",
            "type": "string"
          },
          "payment_document_id": {
            "description": "Payment document ID to link to claims",
            "example": "abc12345-def6-7890-ghij-klmnopqrstuv",
            "format": "uuid",
            "type": "string"
          }
        },
        "required": [
          "claims_document_id",
          "payment_document_id"
        ],
        "type": "object"
      },
      "LinkDocumentRequest": {
        "properties": {
          "bankTransactionId": {
            "description": "Bank transaction to link documents to",
            "format": "uuid",
            "type": "string"
          },
          "createJournalEntry": {
            "default": true,
            "description": "Whether to create a journal entry",
            "type": "boolean"
          },
          "journalOptions": {
            "properties": {
              "accountOverrides": {
                "items": {
                  "properties": {
                    "accountCode": {
                      "type": "string"
                    },
                    "accountName": {
                      "type": "string"
                    },
                    "amount": {
                      "type": "number"
                    },
                    "taxCategory": {
                      "type": "string"
                    }
                  },
                  "type": "object"
                },
                "type": "array"
              },
              "useAiSuggestion": {
                "default": true,
                "type": "boolean"
              }
            },
            "type": "object"
          },
          "linkageType": {
            "$ref": "#/components/schemas/LinkageType",
            "description": "Default linkage type for all links"
          },
          "links": {
            "description": "Array of documents to link",
            "items": {
              "$ref": "#/components/schemas/LinkItem"
            },
            "minItems": 1,
            "type": "array"
          }
        },
        "required": [
          "bankTransactionId",
          "links"
        ],
        "type": "object"
      },
      "LinkDocumentResponse": {
        "properties": {
          "auditLogIds": {
            "description": "Audit log entry IDs for compliance",
            "items": {
              "format": "uuid",
              "type": "string"
            },
            "type": "array"
          },
          "journalEntry": {
            "properties": {
              "date": {
                "type": "string"
              },
              "description": {
                "type": "string"
              },
              "entries": {
                "items": {
                  "properties": {
                    "accountCode": {
                      "type": "string"
                    },
                    "accountName": {
                      "type": "string"
                    },
                    "amount": {
                      "type": "number"
                    },
                    "isDebit": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                },
                "type": "array"
              }
            },
            "type": "object"
          },
          "journalEntryId": {
            "description": "Created journal entry ID (if createJournalEntry was true)",
            "format": "uuid",
            "type": "string"
          },
          "linkIds": {
            "description": "Created link IDs",
            "items": {
              "format": "uuid",
              "type": "string"
            },
            "type": "array"
          },
          "success": {
            "type": "boolean"
          },
          "warnings": {
            "description": "Warning messages (e.g., duplicate links skipped)",
            "items": {
              "type": "string"
            },
            "type": "array"
          }
        },
        "type": "object"
      },
      "LinkItem": {
        "properties": {
          "amount": {
            "description": "Partial amount for split payments",
            "type": "number"
          },
          "documentId": {
            "description": "Document ID to link",
            "format": "uuid",
            "type": "string"
          },
          "documentType": {
            "$ref": "#/components/schemas/DocumentType"
          },
          "linkageType": {
            "$ref": "#/components/schemas/LinkageType"
          },
          "note": {
            "description": "Optional note for the link",
            "type": "string"
          }
        },
        "required": [
          "documentId",
          "documentType"
        ],
        "type": "object"
      },
      "LinkTravelToClaimsRequest": {
        "properties": {
          "claims_document_id": {
            "description": "Claims document ID to link to travel report",
            "example": "456e7890-f12a-34b5-c678-901234567890",
            "format": "uuid",
            "type": "string"
          },
          "travel_document_id": {
            "description": "Travel report document ID to link",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          }
        },
        "required": [
          "travel_document_id",
          "claims_document_id"
        ],
        "type": "object"
      },
      "LinkWithDocument": {
        "properties": {
          "allocatedAmount": {
            "type": "number"
          },
          "auditLogs": {
            "description": "Audit history (if includeAuditLog=true)",
            "items": {
              "type": "object"
            },
            "type": "array"
          },
          "bankTransactionId": {
            "format": "uuid",
            "type": "string"
          },
          "createdAt": {
            "format": "date-time",
            "type": "string"
          },
          "document": {
            "$ref": "#/components/schemas/EnrichedDocument",
            "description": "Enriched document with file details (v4.17)"
          },
          "documentId": {
            "format": "uuid",
            "type": "string"
          },
          "documentType": {
            "type": "string"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "linkageType": {
            "$ref": "#/components/schemas/LinkageType"
          },
          "note": {
            "type": "string"
          }
        },
        "type": "object"
      },
      "LinkageType": {
        "description": "17 linkage types for document-transaction relationships",
        "enum": [
          "direct_expense",
          "reimbursement",
          "payroll",
          "cc_payment",
          "invoice_payment",
          "tax_payment",
          "loan_payment",
          "advance_payment",
          "refund_issued",
          "withholding_tax",
          "fixed_asset",
          "revenue",
          "invoice_receipt",
          "loan_receipt",
          "deposit_received",
          "refund_received",
          "transfer",
          "other"
        ],
        "type": "string"
      },
      "LinkedCountsResponse": {
        "description": "Batch response for linked document counts",
        "properties": {
          "counts": {
            "additionalProperties": {
              "$ref": "#/components/schemas/TransactionLinkedCount"
            },
            "description": "Map of transaction IDs to their linked counts",
            "example": {
              "550e8400-e29b-41d4-a716-446655440001": {
                "documentCount": 2,
                "hasJournal": true,
                "processingStatus": "complete"
              },
              "550e8400-e29b-41d4-a716-446655440002": {
                "documentCount": 0,
                "hasJournal": false,
                "processingStatus": "unprocessed"
              }
            },
            "type": "object"
          },
          "foundIds": {
            "description": "Transaction IDs that were found and belong to the user",
            "example": [
              "550e8400-e29b-41d4-a716-446655440001",
              "550e8400-e29b-41d4-a716-446655440002"
            ],
            "items": {
              "format": "uuid",
              "type": "string"
            },
            "type": "array"
          },
          "notFoundIds": {
            "description": "Transaction IDs that were not found or do not belong to the user",
            "example": [
              "550e8400-e29b-41d4-a716-446655440003"
            ],
            "items": {
              "format": "uuid",
              "type": "string"
            },
            "type": "array"
          },
          "requestedIds": {
            "description": "List of valid transaction IDs that were requested",
            "example": [
              "550e8400-e29b-41d4-a716-446655440001",
              "550e8400-e29b-41d4-a716-446655440002",
              "550e8400-e29b-41d4-a716-446655440003"
            ],
            "items": {
              "format": "uuid",
              "type": "string"
            },
            "type": "array"
          }
        },
        "required": [
          "counts",
          "requestedIds",
          "foundIds",
          "notFoundIds"
        ],
        "type": "object"
      },
      "LinkedDocument": {
        "description": "Linked document response (camelCase - auto-converted from snake_case)",
        "properties": {
          "allocatedAmount": {
            "description": "Amount allocated from this document",
            "type": "number"
          },
          "amount": {
            "description": "Document amount (extracted from content)",
            "type": "number"
          },
          "category": {
            "description": "Link category",
            "type": "string"
          },
          "id": {
            "description": "Document ID",
            "format": "uuid",
            "type": "string"
          },
          "issueDate": {
            "description": "Issue date in YYYYMMDD format",
            "type": "integer"
          },
          "linkId": {
            "description": "Link record ID",
            "format": "uuid",
            "type": "string"
          },
          "linkedAt": {
            "description": "When the document was linked",
            "format": "date-time",
            "type": "string"
          },
          "name": {
            "description": "Document name",
            "type": "string"
          },
          "note": {
            "description": "Link note",
            "type": "string"
          },
          "type": {
            "description": "Document type",
            "enum": [
              "receipt",
              "invoice"
            ],
            "type": "string"
          },
          "vendorName": {
            "description": "Vendor name (extracted from content)",
            "type": "string"
          }
        },
        "type": "object"
      },
      "LivenessResponse": {
        "properties": {
          "alive": {
            "example": true,
            "type": "boolean"
          },
          "requestId": {
            "format": "uuid",
            "type": "string"
          },
          "timestamp": {
            "format": "date-time",
            "type": "string"
          }
        },
        "type": "object"
      },
      "LoadingState": {
        "properties": {
          "loading": {
            "properties": {
              "estimatedSeconds": {
                "nullable": true,
                "type": "number"
              },
              "message": {
                "type": "string"
              },
              "plain": {
                "type": "string"
              },
              "tips": {
                "items": {
                  "type": "string"
                },
                "nullable": true,
                "type": "array"
              }
            },
            "type": "object"
          }
        },
        "type": "object"
      },
      "LockDocumentRequest": {
        "properties": {
          "isLocked": {
            "description": "Set to true to lock the document, false to unlock",
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "isLocked"
        ],
        "type": "object"
      },
      "LockDocumentResponse": {
        "properties": {
          "data": {
            "properties": {
              "id": {
                "description": "Document unique identifier",
                "example": "7f1985a3-5583-4ece-943e-e0d759950829",
                "format": "uuid",
                "type": "string"
              },
              "isLocked": {
                "description": "Current lock status of the document",
                "example": true,
                "type": "boolean"
              },
              "lockedAt": {
                "description": "Timestamp when the document was locked (null if unlocked)",
                "example": "2026-01-07T10:30:00Z",
                "format": "date-time",
                "nullable": true,
                "type": "string"
              },
              "lockedBy": {
                "description": "User ID who locked the document (null if unlocked)",
                "example": "789e0123-e45b-67c8-d901-234567890123",
                "format": "uuid",
                "nullable": true,
                "type": "string"
              },
              "updatedAt": {
                "description": "Last update timestamp",
                "example": "2026-01-07T10:30:00Z",
                "format": "date-time",
                "type": "string"
              }
            },
            "required": [
              "id",
              "isLocked",
              "updatedAt"
            ],
            "type": "object"
          },
          "message": {
            "example": "Document locked successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "LogEntry": {
        "properties": {
          "context": {
            "description": "Log context or module",
            "example": "auth",
            "nullable": true,
            "type": "string"
          },
          "level": {
            "description": "Log level",
            "enum": [
              "error",
              "warn",
              "info",
              "debug"
            ],
            "example": "info",
            "type": "string"
          },
          "message": {
            "description": "Log message",
            "example": "User authentication successful",
            "type": "string"
          },
          "metadata": {
            "additionalProperties": true,
            "description": "Additional log metadata",
            "nullable": true,
            "type": "object"
          },
          "requestId": {
            "description": "Request correlation ID",
            "example": "req_123456",
            "nullable": true,
            "type": "string"
          },
          "timestamp": {
            "description": "Log entry timestamp in ISO format",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "userId": {
            "description": "User ID if applicable",
            "example": "user_789",
            "nullable": true,
            "type": "string"
          }
        },
        "required": [
          "timestamp",
          "level",
          "message"
        ],
        "type": "object"
      },
      "LogFilter": {
        "properties": {
          "context": {
            "description": "Filter by context",
            "nullable": true,
            "type": "string"
          },
          "endTime": {
            "description": "Filter logs before this time",
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "level": {
            "description": "Filter by log level",
            "enum": [
              "error",
              "warn",
              "info",
              "debug"
            ],
            "nullable": true,
            "type": "string"
          },
          "limit": {
            "default": 100,
            "description": "Maximum number of logs to return",
            "maximum": 10000,
            "minimum": 1,
            "type": "integer"
          },
          "requestId": {
            "description": "Filter by request ID",
            "nullable": true,
            "type": "string"
          },
          "search": {
            "description": "Search in log messages",
            "nullable": true,
            "type": "string"
          },
          "startTime": {
            "description": "Filter logs after this time",
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "userId": {
            "description": "Filter by user ID",
            "nullable": true,
            "type": "string"
          }
        },
        "type": "object"
      },
      "LogStats": {
        "properties": {
          "byContext": {
            "additionalProperties": {
              "type": "number"
            },
            "description": "Log counts by context",
            "example": {
              "api": 45,
              "auth": 30,
              "database": 25
            },
            "type": "object"
          },
          "byLevel": {
            "additionalProperties": {
              "type": "number"
            },
            "description": "Log counts by level",
            "example": {
              "debug": 50,
              "error": 5,
              "info": 100,
              "warn": 20
            },
            "type": "object"
          },
          "recentErrors": {
            "description": "Recent error log entries",
            "items": {
              "$ref": "#/components/schemas/LogEntry"
            },
            "type": "array"
          },
          "total": {
            "description": "Total number of logs in buffer",
            "example": 1500,
            "type": "number"
          }
        },
        "required": [
          "total",
          "byLevel",
          "byContext",
          "recentErrors"
        ],
        "type": "object"
      },
      "LogStatsResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/LogStats"
          },
          "message": {
            "example": "Log statistics retrieved",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "LoginResponse": {
        "properties": {
          "achievements_unlocked": {
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "current_streak": {
            "example": 7,
            "type": "integer"
          },
          "longest_streak": {
            "example": 30,
            "type": "integer"
          },
          "streak_multiplier": {
            "example": 1.1,
            "type": "number"
          },
          "xp_awarded": {
            "example": 15,
            "type": "integer"
          }
        },
        "type": "object"
      },
      "LogoutSuccessResponse": {
        "properties": {
          "data": {
            "example": "Log out successfully",
            "type": "string"
          },
          "message": {
            "example": "User logged out successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "LogsResponse": {
        "properties": {
          "data": {
            "description": "Log entries",
            "items": {
              "$ref": "#/components/schemas/LogEntry"
            },
            "type": "array"
          },
          "message": {
            "example": "Retrieved 50 log entries",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "MLITGISAPICode": {
        "description": "MLIT GIS API layer code",
        "enum": [
          "XKT002",
          "XKT006",
          "XKT010",
          "XKT014",
          "XKT017",
          "XKT026",
          "XPT001",
          "XPT002"
        ],
        "example": "XKT002",
        "type": "string"
      },
      "ManualTriggerInfo": {
        "properties": {
          "available": {
            "description": "Whether manual triggers are available in current environment",
            "example": true,
            "type": "boolean"
          },
          "note": {
            "description": "Information about manual trigger availability",
            "example": "Manual triggers are only available in development and staging",
            "type": "string"
          }
        },
        "required": [
          "available",
          "note"
        ],
        "type": "object"
      },
      "MapboxConfigResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/MapboxConfiguration"
          },
          "message": {
            "example": "Mapbox is configured",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          },
          "warning": {
            "description": "Security warning if applicable",
            "example": "Using secret token in frontend - security risk!",
            "type": "string"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "MapboxConfiguration": {
        "properties": {
          "attributionRequired": {
            "description": "Required attribution strings",
            "example": [
              "© Mapbox",
              "© OpenStreetMap",
              "出典：国土交通省「不動産情報ライブラリ」"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "availableStyles": {
            "properties": {
              "dark": {
                "example": "mapbox://styles/mapbox/dark-v11",
                "type": "string"
              },
              "light": {
                "example": "mapbox://styles/mapbox/light-v11",
                "type": "string"
              },
              "outdoors": {
                "example": "mapbox://styles/mapbox/outdoors-v12",
                "type": "string"
              },
              "satellite": {
                "example": "mapbox://styles/mapbox/satellite-streets-v12",
                "type": "string"
              },
              "streets": {
                "example": "mapbox://styles/mapbox/streets-v12",
                "type": "string"
              }
            },
            "type": "object"
          },
          "bestPractices": {
            "properties": {
              "docsUrl": {
                "example": "https://docs.mapbox.com/help/dive-deeper/how-to-use-mapbox-securely/",
                "type": "string"
              },
              "separateTokens": {
                "example": "Use separate tokens per application",
                "type": "string"
              },
              "tokenRotation": {
                "example": "Rotate tokens periodically",
                "type": "string"
              },
              "urlRestrictions": {
                "example": "Enable URL restrictions in Mapbox console for production",
                "type": "string"
              }
            },
            "type": "object"
          },
          "configured": {
            "description": "Whether Mapbox is properly configured",
            "example": true,
            "type": "boolean"
          },
          "defaultCenter": {
            "$ref": "#/components/schemas/Coordinates",
            "description": "Default map center (Tokyo)"
          },
          "defaultZoom": {
            "description": "Default zoom level",
            "example": 10,
            "type": "integer"
          },
          "fixUrl": {
            "description": "URL to fix security issues",
            "example": "https://console.mapbox.com/account/access-tokens/",
            "type": "string"
          },
          "mapStyle": {
            "description": "Default map style URL",
            "example": "mapbox://styles/mapbox/light-v11",
            "type": "string"
          },
          "securityIssue": {
            "description": "Whether there are security issues with the token",
            "example": false,
            "type": "boolean"
          },
          "token": {
            "description": "Mapbox access token (null if not configured)",
            "example": "pk.eyJ1IjoiZXhhbXBsZSIsImEiOiJjbGV4YW1wbGUifQ.example",
            "type": "string"
          },
          "tokenType": {
            "$ref": "#/components/schemas/TokenType"
          }
        },
        "required": [
          "configured",
          "tokenType",
          "mapStyle",
          "availableStyles",
          "defaultCenter",
          "defaultZoom",
          "attributionRequired",
          "bestPractices"
        ],
        "type": "object"
      },
      "MarkAsPaidRequest": {
        "properties": {
          "notes": {
            "description": "Optional notes about the payment",
            "example": "3月分源泉所得税納付",
            "type": "string"
          },
          "payment_date": {
            "description": "Date payment was made to tax authorities (YYYYMMDD format)",
            "example": 20240410,
            "maximum": 29991231,
            "minimum": 19000101,
            "type": "integer"
          },
          "payment_reference": {
            "description": "Payment reference number from bank or tax authority",
            "example": "REF-2024-001",
            "type": "string"
          },
          "record_ids": {
            "description": "Array of withholding tax record IDs to mark as paid",
            "example": [
              "123e4567-e89b-12d3-a456-426614174000",
              "223e4567-e89b-12d3-a456-426614174001"
            ],
            "items": {
              "format": "uuid",
              "type": "string"
            },
            "minItems": 1,
            "type": "array"
          }
        },
        "required": [
          "record_ids",
          "payment_date"
        ],
        "type": "object"
      },
      "MarkAsPaidResponse": {
        "properties": {
          "data": {
            "properties": {
              "paymentDate": {
                "description": "Payment date recorded",
                "example": 20240410,
                "type": "integer"
              },
              "recordIds": {
                "description": "IDs of records that were updated",
                "items": {
                  "format": "uuid",
                  "type": "string"
                },
                "type": "array"
              },
              "totalWithholdingAmount": {
                "description": "Total withholding amount paid",
                "example": 255250,
                "format": "decimal",
                "type": "number"
              },
              "updatedCount": {
                "description": "Number of records updated",
                "example": 5,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "5件の源泉徴収を納付済みに更新しました",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "MatchDocumentsApiResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/MatchDocumentsResponse"
          },
          "message": {
            "example": "Documents matched successfully",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "MatchDocumentsRequest": {
        "properties": {
          "searchScope": {
            "$ref": "#/components/schemas/SearchScope"
          },
          "transaction": {
            "$ref": "#/components/schemas/TransactionInput"
          }
        },
        "required": [
          "transaction"
        ],
        "type": "object"
      },
      "MatchDocumentsResponse": {
        "properties": {
          "alternativeMatches": {
            "description": "Alternative match options",
            "items": {
              "properties": {
                "documentId": {
                  "example": "doc_789",
                  "type": "string"
                },
                "matchScore": {
                  "example": 0.75,
                  "format": "double",
                  "type": "number"
                },
                "reason": {
                  "example": "金額が近似",
                  "type": "string"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "bestMatch": {
            "$ref": "#/components/schemas/DocumentMatch"
          },
          "matchType": {
            "$ref": "#/components/schemas/MatchType"
          },
          "noMatchReason": {
            "description": "Reason for no match (if applicable)",
            "example": "該当期間に一致する文書が見つかりませんでした",
            "type": "string"
          },
          "reasoning": {
            "description": "AI reasoning for match results",
            "example": "金額と日付の完全一致により高い信頼度でマッチングしました",
            "type": "string"
          },
          "splitMatch": {
            "$ref": "#/components/schemas/SplitMatchResult"
          }
        },
        "required": [
          "matchType",
          "reasoning"
        ],
        "type": "object"
      },
      "MatchSuggestion": {
        "properties": {
          "amount": {
            "description": "Journal entry amount in JPY",
            "example": 15000,
            "format": "decimal",
            "type": "number"
          },
          "amount_difference": {
            "description": "Difference between bank and journal amounts",
            "example": 0,
            "format": "decimal",
            "type": "number"
          },
          "date_difference_days": {
            "description": "Days difference between bank and journal dates",
            "example": 0,
            "type": "integer"
          },
          "description": {
            "description": "Journal entry description",
            "example": "オフィス用品購入",
            "type": "string"
          },
          "entry_date": {
            "description": "Journal entry date in YYYYMMDD format",
            "example": 20240115,
            "type": "integer"
          },
          "entry_number": {
            "description": "Journal entry number for reference",
            "example": "JE-2024-001234",
            "type": "string"
          },
          "journal_entry_id": {
            "description": "Journal entry unique identifier",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "match_confidence": {
            "description": "Match confidence score (0.0 to 1.0)",
            "example": 0.95,
            "format": "decimal",
            "maximum": 1,
            "minimum": 0,
            "type": "number"
          },
          "match_reason": {
            "description": "Explanation for the match suggestion",
            "example": "Exact amount and date match with similar description",
            "type": "string"
          },
          "match_type": {
            "$ref": "#/components/schemas/MatchType"
          },
          "suggested_adjustments": {
            "description": "Suggested adjustments for reconciliation differences",
            "items": {
              "properties": {
                "account_code": {
                  "type": "string"
                },
                "amount": {
                  "format": "decimal",
                  "type": "number"
                },
                "description": {
                  "type": "string"
                },
                "type": {
                  "$ref": "#/components/schemas/AdjustmentType"
                }
              },
              "type": "object"
            },
            "type": "array"
          }
        },
        "required": [
          "journal_entry_id",
          "entry_number",
          "description",
          "amount",
          "entry_date",
          "match_confidence",
          "match_type",
          "match_reason",
          "amount_difference",
          "date_difference_days"
        ],
        "type": "object"
      },
      "MatchSuggestionsResponse": {
        "properties": {
          "data": {
            "items": {
              "$ref": "#/components/schemas/MatchSuggestion"
            },
            "type": "array"
          },
          "message": {
            "example": "Match suggestions retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "MatchType": {
        "description": "Type of match between bank transaction and journal entry",
        "enum": [
          "exact",
          "amount_adjusted",
          "partial",
          "combined",
          "split"
        ],
        "example": "exact",
        "type": "string"
      },
      "MatchedDocument": {
        "properties": {
          "applicant": {
            "description": "Expense applicant name",
            "example": "田中太郎",
            "type": "string"
          },
          "documentId": {
            "description": "Document identifier",
            "example": "doc_456789",
            "type": "string"
          },
          "documentType": {
            "$ref": "#/components/schemas/DocumentType"
          },
          "expenseBreakdown": {
            "description": "Breakdown of expenses by category",
            "items": {
              "$ref": "#/components/schemas/ExpenseBreakdownItem"
            },
            "type": "array"
          },
          "totalAmount": {
            "description": "Total document amount",
            "example": 15000,
            "format": "decimal",
            "type": "number"
          },
          "vendor": {
            "description": "Vendor or supplier name",
            "example": "JR東日本",
            "type": "string"
          }
        },
        "required": [
          "documentId",
          "documentType",
          "totalAmount"
        ],
        "type": "object"
      },
      "McpJsonRpcRequest": {
        "properties": {
          "id": {
            "oneOf": [
              {
                "type": "string"
              },
              {
                "type": "integer"
              }
            ]
          },
          "jsonrpc": {
            "enum": [
              "2.0"
            ],
            "type": "string"
          },
          "method": {
            "description": "initialize, notifications/initialized, tools/list, tools/call, ping",
            "example": "tools/call",
            "type": "string"
          },
          "params": {
            "additionalProperties": true,
            "type": "object"
          }
        },
        "required": [
          "jsonrpc",
          "method"
        ],
        "type": "object"
      },
      "McpJsonRpcResponse": {
        "properties": {
          "error": {
            "properties": {
              "code": {
                "type": "integer"
              },
              "message": {
                "type": "string"
              }
            },
            "type": "object"
          },
          "id": {
            "nullable": true,
            "oneOf": [
              {
                "type": "string"
              },
              {
                "type": "integer"
              }
            ]
          },
          "jsonrpc": {
            "enum": [
              "2.0"
            ],
            "type": "string"
          },
          "result": {
            "additionalProperties": true,
            "type": "object"
          }
        },
        "required": [
          "jsonrpc"
        ],
        "type": "object"
      },
      "McpProtectedResourceMetadata": {
        "description": "RFC 9728 Protected Resource Metadata (snake_case by spec).",
        "properties": {
          "authorization_servers": {
            "example": [
              "https://kxifbgoucsorjxzcauih.supabase.co/auth/v1"
            ],
            "items": {
              "format": "uri",
              "type": "string"
            },
            "type": "array"
          },
          "bearer_methods_supported": {
            "items": {
              "enum": [
                "header"
              ],
              "type": "string"
            },
            "type": "array"
          },
          "resource": {
            "example": "https://solo-boss.kensaur.us/api/mcp",
            "format": "uri",
            "type": "string"
          },
          "resource_name": {
            "example": "一人社長クラウド (Solo Boss Cloud)",
            "type": "string"
          },
          "scopes_supported": {
            "example": [
              "openid",
              "email",
              "profile"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          }
        },
        "required": [
          "resource",
          "authorization_servers",
          "scopes_supported",
          "bearer_methods_supported"
        ],
        "type": "object"
      },
      "MemberInviteCreated": {
        "properties": {
          "email": {
            "format": "email",
            "type": "string"
          },
          "expiresAt": {
            "format": "date-time",
            "type": "string"
          },
          "inviteId": {
            "format": "uuid",
            "type": "string"
          },
          "inviteUrl": {
            "description": "Copyable accept URL for the invitee",
            "type": "string"
          },
          "role": {
            "description": "Member role. Owners are implicit and not stored as a member row.",
            "enum": [
              "viewer",
              "editor",
              "admin"
            ],
            "type": "string"
          }
        },
        "type": "object"
      },
      "MemberInviteRequest": {
        "properties": {
          "email": {
            "format": "email",
            "type": "string"
          },
          "role": {
            "default": "viewer",
            "description": "Member role. Owners are implicit and not stored as a member row.",
            "enum": [
              "viewer",
              "editor",
              "admin"
            ],
            "type": "string"
          }
        },
        "required": [
          "email"
        ],
        "type": "object"
      },
      "MemberRoleRequest": {
        "properties": {
          "role": {
            "description": "Member role. Owners are implicit and not stored as a member row.",
            "enum": [
              "viewer",
              "editor",
              "admin"
            ],
            "type": "string"
          }
        },
        "required": [
          "role"
        ],
        "type": "object"
      },
      "Message": {
        "properties": {
          "content": {
            "description": "The content of the message",
            "example": "Hello, how can you help me today?",
            "type": "string"
          },
          "role": {
            "description": "The role of the message sender",
            "enum": [
              "system",
              "user",
              "assistant"
            ],
            "example": "user",
            "type": "string"
          }
        },
        "required": [
          "role",
          "content"
        ],
        "type": "object"
      },
      "MessageCategory": {
        "properties": {
          "category": {
            "example": "expense",
            "type": "string"
          },
          "methodCount": {
            "example": 5,
            "type": "integer"
          },
          "methods": {
            "example": [
              "expenseAllOk",
              "expenseNeedsAttention",
              "expenseHomeOffice"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          }
        },
        "type": "object"
      },
      "MethodComparison": {
        "description": "v4.46: Enhanced method comparison response",
        "properties": {
          "eligibility": {
            "$ref": "#/components/schemas/TaxEligibility"
          },
          "general": {
            "$ref": "#/components/schemas/TaxMethodDetail"
          },
          "recommendation": {
            "$ref": "#/components/schemas/TaxRecommendationDetail"
          },
          "simplified": {
            "$ref": "#/components/schemas/TaxMethodDetail"
          },
          "special_20": {
            "$ref": "#/components/schemas/TaxMethodDetail"
          }
        },
        "required": [
          "general",
          "recommendation",
          "eligibility"
        ],
        "type": "object"
      },
      "MethodComparisonResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/MethodComparison"
          },
          "message": {
            "example": "計算方法を比較しました",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "MigrationInfo": {
        "properties": {
          "applied_at": {
            "description": "Migration application timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "checksum": {
            "description": "Migration checksum",
            "example": "abc123def456",
            "type": "string"
          },
          "id": {
            "description": "Migration ID",
            "example": "20240115103000_init",
            "type": "string"
          },
          "name": {
            "description": "Migration name",
            "example": "20240115103000_init",
            "type": "string"
          }
        },
        "required": [
          "id",
          "name",
          "applied_at",
          "checksum"
        ],
        "type": "object"
      },
      "MigrationStatus": {
        "properties": {
          "lastMigration": {
            "allOf": [
              {
                "$ref": "#/components/schemas/MigrationInfo"
              }
            ],
            "description": "Last applied migration",
            "nullable": true
          },
          "pendingMigrations": {
            "description": "Pending migration names",
            "example": [
              "20240116120000_add_indexes"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "schemaVersion": {
            "description": "Current schema version",
            "example": "1.2.3",
            "type": "string"
          },
          "totalMigrations": {
            "description": "Total applied migrations",
            "example": 15,
            "type": "number"
          }
        },
        "required": [
          "totalMigrations",
          "lastMigration",
          "pendingMigrations",
          "schemaVersion"
        ],
        "type": "object"
      },
      "MigrationStatusResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/MigrationStatus"
          },
          "message": {
            "example": "Migration status retrieved",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "MigrationsResponse": {
        "properties": {
          "data": {
            "description": "Migration history",
            "items": {
              "$ref": "#/components/schemas/MigrationInfo"
            },
            "type": "array"
          },
          "message": {
            "example": "Found 15 migrations",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ModelBreakdownResponse": {
        "properties": {
          "items": {
            "items": {
              "properties": {
                "latency_p50_ms": {
                  "example": 1100,
                  "type": "number"
                },
                "model": {
                  "example": "gpt-4o",
                  "type": "string"
                },
                "requests": {
                  "example": 120,
                  "type": "integer"
                },
                "total_cost": {
                  "example": 12.34,
                  "type": "number"
                },
                "total_tokens": {
                  "example": 45000,
                  "type": "integer"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "source": {
            "enum": [
              "langfuse",
              "local"
            ],
            "example": "langfuse",
            "type": "string"
          }
        },
        "required": [
          "items",
          "source"
        ],
        "type": "object"
      },
      "ModelCapability": {
        "description": "AI model capability classification",
        "enum": [
          "text",
          "vision",
          "code",
          "function_calling",
          "streaming"
        ],
        "example": "text",
        "type": "string"
      },
      "ModelField": {
        "properties": {
          "default": {
            "description": "Default value if any",
            "example": "true",
            "nullable": true,
            "type": "string"
          },
          "description": {
            "description": "Field description",
            "example": "Primary key",
            "nullable": true,
            "type": "string"
          },
          "name": {
            "description": "Field name",
            "example": "id",
            "type": "string"
          },
          "nullable": {
            "description": "Whether field can be null",
            "example": false,
            "type": "boolean"
          },
          "type": {
            "description": "Field data type",
            "example": "UUID",
            "type": "string"
          }
        },
        "required": [
          "name",
          "type",
          "nullable"
        ],
        "type": "object"
      },
      "ModelRelation": {
        "properties": {
          "description": {
            "description": "Relation description",
            "nullable": true,
            "type": "string"
          },
          "name": {
            "description": "Relation name",
            "example": "owner",
            "type": "string"
          },
          "relatedModel": {
            "description": "Related model name",
            "example": "user_profiles",
            "type": "string"
          },
          "type": {
            "description": "Relation type",
            "enum": [
              "one-to-one",
              "one-to-many",
              "many-to-one"
            ],
            "example": "many-to-one",
            "type": "string"
          }
        },
        "required": [
          "name",
          "type",
          "relatedModel"
        ],
        "type": "object"
      },
      "ModelValidationResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/ModelValidationResult"
          },
          "message": {
            "example": "Model is valid",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ModelValidationResult": {
        "properties": {
          "isValid": {
            "description": "Whether model is valid for the provider",
            "example": true,
            "type": "boolean"
          },
          "model": {
            "allOf": [
              {
                "$ref": "#/components/schemas/AIModel"
              },
              {
                "nullable": true
              }
            ],
            "description": "Model details if valid"
          },
          "model_id": {
            "description": "Model identifier being validated",
            "example": "gpt-6-sol",
            "type": "string"
          },
          "provider": {
            "description": "Provider identifier",
            "example": "openai",
            "type": "string"
          },
          "suggestedDefault": {
            "description": "Suggested default model if invalid",
            "example": "gpt-6-luna",
            "type": "string"
          }
        },
        "required": [
          "provider",
          "model_id",
          "isValid"
        ],
        "type": "object"
      },
      "ModelsResponse": {
        "properties": {
          "data": {
            "items": {
              "$ref": "#/components/schemas/AIModel"
            },
            "type": "array"
          },
          "message": {
            "example": "Models retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "MoneyTrail": {
        "properties": {
          "nodes": {
            "description": "evidence → expense → trip → claim → pay_slip → payout → bank → journal → other; by date within a stage.",
            "items": {
              "$ref": "#/components/schemas/MoneyTrailNode"
            },
            "type": "array"
          },
          "origin": {
            "properties": {
              "id": {
                "format": "uuid",
                "type": "string"
              },
              "kind": {
                "enum": [
                  "file",
                  "document",
                  "bank_transaction",
                  "expense"
                ],
                "type": "string"
              }
            },
            "required": [
              "kind",
              "id"
            ],
            "type": "object"
          },
          "truncated": {
            "description": "The walk stopped at its node cap (40).",
            "type": "boolean"
          },
          "verdict": {
            "properties": {
              "detail": {
                "nullable": true,
                "type": "string"
              },
              "headline": {
                "example": "8月25日の合算精算 ¥123,456 に含まれています。振込の照合待ちです",
                "type": "string"
              },
              "state": {
                "enum": [
                  "paid_by_company",
                  "reimbursed",
                  "awaiting_transfer",
                  "claimed_unpaid",
                  "unclaimed",
                  "received",
                  "unrecorded",
                  "unknown"
                ],
                "type": "string"
              }
            },
            "required": [
              "state",
              "headline",
              "detail"
            ],
            "type": "object"
          }
        },
        "required": [
          "origin",
          "verdict",
          "nodes",
          "truncated"
        ],
        "type": "object"
      },
      "MoneyTrailNode": {
        "properties": {
          "amountYen": {
            "example": 12345,
            "nullable": true,
            "type": "number"
          },
          "date": {
            "example": "2026-07-31",
            "format": "date",
            "nullable": true,
            "type": "string"
          },
          "documentType": {
            "example": "claims",
            "nullable": true,
            "type": "string"
          },
          "href": {
            "example": "/view/claims/00000000-0000-4000-8000-000000000001",
            "type": "string"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "isOrigin": {
            "type": "boolean"
          },
          "kind": {
            "enum": [
              "file",
              "expense",
              "document",
              "bank_transaction",
              "journal_entry"
            ],
            "type": "string"
          },
          "stage": {
            "description": "From the record itself (kind / document_type), never from the link name.",
            "enum": [
              "evidence",
              "expense",
              "trip",
              "claim",
              "pay_slip",
              "payout",
              "bank",
              "journal",
              "other"
            ],
            "type": "string"
          },
          "status": {
            "nullable": true,
            "properties": {
              "label": {
                "example": "振込待ち",
                "type": "string"
              },
              "tone": {
                "enum": [
                  "done",
                  "waiting",
                  "danger",
                  "info",
                  "neutral"
                ],
                "type": "string"
              }
            },
            "required": [
              "tone",
              "label"
            ],
            "type": "object"
          },
          "title": {
            "example": "20260731-20260803_経費精算書_出張_JPY12345",
            "type": "string"
          },
          "via": {
            "description": "The link that reached it: a relationship_type or a link table (null for the origin).",
            "example": "document_expenses",
            "nullable": true,
            "type": "string"
          }
        },
        "required": [
          "kind",
          "id",
          "stage",
          "title",
          "date",
          "amountYen",
          "status",
          "href",
          "documentType",
          "via",
          "isOrigin"
        ],
        "type": "object"
      },
      "MonthEndValidation": {
        "properties": {
          "excluded_count": {
            "description": "Number of excluded transactions",
            "example": 2,
            "type": "integer"
          },
          "period": {
            "description": "Validation period (YYYY-MM format)",
            "example": "2024-01",
            "type": "string"
          },
          "recommendations": {
            "description": "Recommendations for improving reconciliation",
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "reconciled_count": {
            "description": "Number of reconciled transactions",
            "example": 145,
            "type": "integer"
          },
          "reconciliation_rate": {
            "description": "Reconciliation completion rate",
            "example": 0.967,
            "format": "decimal",
            "maximum": 1,
            "minimum": 0,
            "type": "number"
          },
          "suspense_count": {
            "description": "Number of transactions in suspense",
            "example": 1,
            "type": "integer"
          },
          "total_transactions": {
            "description": "Total bank transactions in period",
            "example": 150,
            "type": "integer"
          },
          "total_unreconciled_amount": {
            "description": "Total amount of unreconciled transactions",
            "example": 25000,
            "format": "decimal",
            "type": "number"
          },
          "unreconciled_count": {
            "description": "Number of unreconciled transactions",
            "example": 5,
            "type": "integer"
          },
          "validation_issues": {
            "description": "Validation issues found during month-end check",
            "items": {
              "properties": {
                "affected_transactions": {
                  "type": "integer"
                },
                "description": {
                  "type": "string"
                },
                "severity": {
                  "enum": [
                    "error",
                    "warning",
                    "info"
                  ],
                  "type": "string"
                },
                "total_amount": {
                  "format": "decimal",
                  "type": "number"
                },
                "type": {
                  "example": "large_unreconciled_amount",
                  "type": "string"
                }
              },
              "type": "object"
            },
            "type": "array"
          }
        },
        "required": [
          "period",
          "total_transactions",
          "reconciled_count",
          "unreconciled_count",
          "excluded_count",
          "suspense_count",
          "reconciliation_rate",
          "total_unreconciled_amount",
          "validation_issues",
          "recommendations"
        ],
        "type": "object"
      },
      "MonthEndValidationResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/MonthEndValidation"
          },
          "message": {
            "example": "Month-end validation completed successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "MonthlyUsage": {
        "properties": {
          "daily_breakdown": {
            "description": "Daily usage breakdown for the month",
            "items": {
              "properties": {
                "cost": {
                  "example": 2.25,
                  "type": "number"
                },
                "day": {
                  "example": 15,
                  "type": "integer"
                },
                "requests": {
                  "example": 4,
                  "type": "integer"
                },
                "tokens": {
                  "example": 1500,
                  "type": "integer"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "month": {
            "description": "Month of the usage data (1-12)",
            "example": 1,
            "maximum": 12,
            "minimum": 1,
            "type": "integer"
          },
          "operation_summary": {
            "additionalProperties": {
              "properties": {
                "cost": {
                  "type": "number"
                },
                "requests": {
                  "type": "integer"
                },
                "tokens": {
                  "type": "integer"
                }
              },
              "type": "object"
            },
            "description": "Monthly summary by operation type",
            "type": "object"
          },
          "total_cost": {
            "description": "Total estimated cost for the month in USD",
            "example": 67.5,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "total_requests": {
            "description": "Total requests made in the month",
            "example": 120,
            "minimum": 0,
            "type": "integer"
          },
          "total_tokens": {
            "description": "Total tokens used in the month",
            "example": 45000,
            "minimum": 0,
            "type": "integer"
          },
          "year": {
            "description": "Year of the usage data",
            "example": 2024,
            "maximum": 2100,
            "minimum": 2000,
            "type": "integer"
          }
        },
        "required": [
          "year",
          "month",
          "total_tokens",
          "total_requests",
          "total_cost",
          "daily_breakdown",
          "operation_summary"
        ],
        "type": "object"
      },
      "MonthlyUsageResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/MonthlyUsage"
          },
          "message": {
            "example": "Monthly usage statistics retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "MoveFilesToFolderRequest": {
        "properties": {
          "file_ids": {
            "description": "Array of file IDs to move (at least one required)",
            "example": [
              "123e4567-e89b-12d3-a456-426614174000",
              "789e0123-e45b-67c8-d901-234567890123"
            ],
            "items": {
              "format": "uuid",
              "type": "string"
            },
            "minItems": 1,
            "type": "array"
          },
          "folder_id": {
            "description": "Target folder ID for file organization",
            "example": "456e7890-f12a-34b5-c678-901234567890",
            "format": "uuid",
            "type": "string"
          }
        },
        "required": [
          "file_ids",
          "folder_id"
        ],
        "type": "object"
      },
      "MultiOfficeApportionRequest": {
        "properties": {
          "corporateTaxAmount": {
            "description": "法人税額（法人税割の課税標準）。円。",
            "maximum": 10000000000,
            "minimum": 0,
            "type": "integer"
          },
          "fiscalYearEnd": {
            "example": "2026-04-01",
            "pattern": "^\\d{4}-\\d{2}-\\d{2}$",
            "type": "string"
          },
          "fiscalYearStart": {
            "example": "2026-04-01",
            "pattern": "^\\d{4}-\\d{2}-\\d{2}$",
            "type": "string"
          }
        },
        "required": [
          "corporateTaxAmount",
          "fiscalYearStart",
          "fiscalYearEnd"
        ],
        "type": "object"
      },
      "MultiOfficeContextFactRequest": {
        "properties": {
          "answer": {
            "maxLength": 4000,
            "minLength": 1,
            "type": "string"
          },
          "question": {
            "maxLength": 255,
            "minLength": 1,
            "type": "string"
          },
          "topic": {
            "maxLength": 60,
            "minLength": 1,
            "type": "string"
          }
        },
        "required": [
          "topic",
          "question",
          "answer"
        ],
        "type": "object"
      },
      "MultiOfficeCreatePaymentRequest": {
        "properties": {
          "amountYen": {
            "maximum": 1000000000,
            "minimum": 0,
            "type": "integer"
          },
          "cardTransactionRef": {
            "description": "カード納付の決済番号（銀行の出金行がないカード納付の証跡）",
            "maxLength": 100,
            "minLength": 1,
            "type": "string"
          },
          "dueDate": {
            "example": "2026-04-01",
            "pattern": "^\\d{4}-\\d{2}-\\d{2}$",
            "type": "string"
          },
          "evidenceFileId": {
            "description": "控え・領収証書（自分のファイル）",
            "format": "uuid",
            "type": "string"
          },
          "feeYen": {
            "description": "納付手数料（円）",
            "maximum": 100000,
            "minimum": 0,
            "type": "integer"
          },
          "memo": {
            "maxLength": 1000,
            "type": "string"
          },
          "officeId": {
            "format": "uuid",
            "type": "string"
          },
          "paymentChannel": {
            "description": "払い方: 電子申告連動 / ペイジー / クレジットカード（F-REGI） / 窓口 / 口座振替",
            "enum": [
              "eltax_linked",
              "payeasy",
              "credit_card",
              "counter",
              "direct_debit"
            ],
            "type": "string"
          },
          "periodLabel": {
            "maxLength": 60,
            "minLength": 1,
            "type": "string"
          },
          "receiptNumber": {
            "description": "eLTAX の受付番号・納付番号（英数字とハイフン。全角は半角にそろえて受け付けます）",
            "example": "R1-2026-12345678",
            "pattern": "^[A-Za-z0-9][A-Za-z0-9-]{3,49}$",
            "type": "string"
          },
          "taxKind": {
            "enum": [
              "juminzei_kakutei",
              "juminzei_chukan",
              "jigyozei",
              "shokyaku_shisan",
              "other"
            ],
            "type": "string"
          }
        },
        "required": [
          "officeId",
          "taxKind",
          "periodLabel"
        ],
        "type": "object"
      },
      "MultiOfficeCreateRequest": {
        "properties": {
          "address": {
            "maxLength": 255,
            "minLength": 1,
            "type": "string"
          },
          "employeeCount": {
            "default": 0,
            "maximum": 10000,
            "minimum": 0,
            "type": "integer"
          },
          "establishedOn": {
            "description": "設置日 YYYY-MM-DD",
            "example": "2026-04-01",
            "pattern": "^\\d{4}-\\d{2}-\\d{2}$",
            "type": "string"
          },
          "hasBranchRegistration": {
            "default": false,
            "type": "boolean"
          },
          "isHeadOffice": {
            "default": false,
            "type": "boolean"
          },
          "municipalityCode": {
            "description": "市区町村コード（5桁）",
            "pattern": "^\\d{5}$",
            "type": "string"
          },
          "municipalityName": {
            "maxLength": 40,
            "minLength": 1,
            "type": "string"
          },
          "name": {
            "maxLength": 120,
            "minLength": 1,
            "type": "string"
          },
          "notes": {
            "maxLength": 2000,
            "type": "string"
          },
          "postalCode": {
            "description": "123-4567 形式",
            "pattern": "^\\d{3}-?\\d{4}$",
            "type": "string"
          },
          "prefectureCode": {
            "description": "都道府県コード（2桁）",
            "pattern": "^\\d{2}$",
            "type": "string"
          },
          "prefectureName": {
            "maxLength": 20,
            "minLength": 2,
            "type": "string"
          }
        },
        "required": [
          "name",
          "address",
          "prefectureCode",
          "prefectureName",
          "municipalityName",
          "establishedOn"
        ],
        "type": "object"
      },
      "MultiOfficeFilingProgressRequest": {
        "properties": {
          "status": {
            "enum": [
              "todo",
              "in_progress",
              "done"
            ],
            "type": "string"
          },
          "stepKey": {
            "enum": [
              "attachments_teikan",
              "attachments_tokibo",
              "attachments_lease",
              "eltax_add_destination",
              "eltax_review_wait",
              "pref_setti_submit",
              "muni_setti_submit",
              "head_office_idou"
            ],
            "type": "string"
          }
        },
        "required": [
          "stepKey",
          "status"
        ],
        "type": "object"
      },
      "MultiOfficeObligation": {
        "description": "「この事業所で発生する手続き」の1行",
        "properties": {
          "amountYen": {
            "nullable": true,
            "type": "integer"
          },
          "authority": {
            "example": "群馬県",
            "nullable": true,
            "type": "string"
          },
          "deadlineId": {
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "dueDate": {
            "example": "2026-04-01",
            "pattern": "^\\d{4}-\\d{2}-\\d{2}$",
            "type": "string"
          },
          "source": {
            "description": "calendar = 申告カレンダーの行（deadlineId でリンク）、payment_schedule = 納付スケジュール",
            "enum": [
              "calendar",
              "payment_schedule"
            ],
            "type": "string"
          },
          "status": {
            "example": "upcoming",
            "nullable": true,
            "type": "string"
          },
          "title": {
            "example": "法人設立・設置届（群馬県）",
            "type": "string"
          }
        },
        "required": [
          "source",
          "deadlineId",
          "title",
          "authority",
          "dueDate",
          "status",
          "amountYen"
        ],
        "type": "object"
      },
      "MultiOfficeSavedOffice": {
        "additionalProperties": true,
        "description": "保存した事業所と、再計算後の申告カレンダーにあるこの事業所の手続き",
        "properties": {
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "name": {
            "type": "string"
          },
          "obligations": {
            "items": {
              "$ref": "#/components/schemas/MultiOfficeObligation"
            },
            "type": "array"
          },
          "obligationsRefreshed": {
            "description": "false = 再計算に失敗し、保存前の申告カレンダーから一覧を作りました（夜間の再計算で更新されます）",
            "type": "boolean"
          }
        },
        "type": "object"
      },
      "MultiOfficeSimulateRequest": {
        "properties": {
          "establishedOn": {
            "example": "2026-04-01",
            "pattern": "^\\d{4}-\\d{2}-\\d{2}$",
            "type": "string"
          },
          "isTokyoSpecialWard": {
            "default": false,
            "type": "boolean"
          },
          "municipalityCode": {
            "pattern": "^\\d{5}$",
            "type": "string"
          },
          "municipalityName": {
            "maxLength": 40,
            "minLength": 1,
            "type": "string"
          },
          "prefectureCode": {
            "pattern": "^\\d{2}$",
            "type": "string"
          },
          "prefectureName": {
            "maxLength": 20,
            "minLength": 2,
            "type": "string"
          }
        },
        "required": [
          "prefectureCode",
          "prefectureName",
          "municipalityName",
          "establishedOn"
        ],
        "type": "object"
      },
      "MultiOfficeUpdatePaymentRequest": {
        "properties": {
          "amountYen": {
            "maximum": 1000000000,
            "minimum": 0,
            "nullable": true,
            "type": "integer"
          },
          "bankTransactionId": {
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "cardTransactionRef": {
            "description": "カード納付の決済番号（銀行の出金行がないカード納付の証跡）",
            "maxLength": 100,
            "minLength": 1,
            "nullable": true,
            "type": "string"
          },
          "dueDate": {
            "example": "2026-04-01",
            "nullable": true,
            "pattern": "^\\d{4}-\\d{2}-\\d{2}$",
            "type": "string"
          },
          "evidenceFileId": {
            "description": "控え・領収証書（自分のファイル）",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "feeYen": {
            "description": "納付手数料（円）",
            "maximum": 100000,
            "minimum": 0,
            "nullable": true,
            "type": "integer"
          },
          "memo": {
            "maxLength": 1000,
            "nullable": true,
            "type": "string"
          },
          "paidOn": {
            "example": "2026-04-01",
            "nullable": true,
            "pattern": "^\\d{4}-\\d{2}-\\d{2}$",
            "type": "string"
          },
          "paymentChannel": {
            "description": "払い方: 電子申告連動 / ペイジー / クレジットカード（F-REGI） / 窓口 / 口座振替",
            "enum": [
              "eltax_linked",
              "payeasy",
              "credit_card",
              "counter",
              "direct_debit"
            ],
            "nullable": true,
            "type": "string"
          },
          "receiptNumber": {
            "description": "eLTAX の受付番号・納付番号（英数字とハイフン。全角は半角にそろえて受け付けます）",
            "example": "R1-2026-12345678",
            "nullable": true,
            "pattern": "^[A-Za-z0-9][A-Za-z0-9-]{3,49}$",
            "type": "string"
          }
        },
        "type": "object"
      },
      "MultiOfficeUpdateRequest": {
        "description": "All CREATE fields are optional on update, plus closedOn (廃止日).",
        "properties": {
          "address": {
            "maxLength": 255,
            "minLength": 1,
            "type": "string"
          },
          "closedOn": {
            "description": "廃止日 YYYY-MM-DD",
            "example": "2026-04-01",
            "nullable": true,
            "pattern": "^\\d{4}-\\d{2}-\\d{2}$",
            "type": "string"
          },
          "employeeCount": {
            "maximum": 10000,
            "minimum": 0,
            "type": "integer"
          },
          "establishedOn": {
            "example": "2026-04-01",
            "pattern": "^\\d{4}-\\d{2}-\\d{2}$",
            "type": "string"
          },
          "hasBranchRegistration": {
            "type": "boolean"
          },
          "isHeadOffice": {
            "type": "boolean"
          },
          "municipalityCode": {
            "pattern": "^\\d{5}$",
            "type": "string"
          },
          "municipalityName": {
            "maxLength": 40,
            "minLength": 1,
            "type": "string"
          },
          "name": {
            "maxLength": 120,
            "minLength": 1,
            "type": "string"
          },
          "notes": {
            "maxLength": 2000,
            "type": "string"
          },
          "postalCode": {
            "pattern": "^\\d{3}-?\\d{4}$",
            "type": "string"
          },
          "prefectureCode": {
            "pattern": "^\\d{2}$",
            "type": "string"
          },
          "prefectureName": {
            "maxLength": 20,
            "minLength": 2,
            "type": "string"
          }
        },
        "type": "object"
      },
      "MushiTunnelError": {
        "properties": {
          "ok": {
            "example": false,
            "type": "boolean"
          },
          "reason": {
            "description": "Allowlist / config failure reason",
            "enum": [
              "tunnel_not_configured",
              "method_not_allowed",
              "path_not_allowed",
              "project_not_allowed",
              "host_not_allowed"
            ],
            "type": "string"
          }
        },
        "type": "object"
      },
      "MyAccount": {
        "description": "An account the authenticated actor may act inside — their own (role \"owner\") or an owner account they actively belong to. `ownerUserId` is the value sent as the X-Account-Id header to act inside that account.",
        "properties": {
          "avatarUrl": {
            "nullable": true,
            "type": "string"
          },
          "displayName": {
            "nullable": true,
            "type": "string"
          },
          "email": {
            "nullable": true,
            "type": "string"
          },
          "isSelf": {
            "description": "True for the actor's own account",
            "type": "boolean"
          },
          "ownerUserId": {
            "description": "Account owner user id (X-Account-Id value)",
            "format": "uuid",
            "type": "string"
          },
          "role": {
            "description": "\"owner\" for the actor's own account; otherwise the granted membership role",
            "enum": [
              "owner",
              "viewer",
              "editor",
              "admin"
            ],
            "type": "string"
          }
        },
        "required": [
          "ownerUserId",
          "role",
          "isSelf"
        ],
        "type": "object"
      },
      "MyAccountsResponse": {
        "properties": {
          "accounts": {
            "items": {
              "$ref": "#/components/schemas/MyAccount"
            },
            "type": "array"
          }
        },
        "type": "object"
      },
      "NextLevelInfoResponse": {
        "description": "Next level info, null at max level",
        "nullable": true,
        "properties": {
          "level": {
            "example": 2,
            "type": "integer"
          },
          "minXP": {
            "example": 100,
            "type": "integer"
          },
          "name": {
            "properties": {
              "en": {
                "example": "Entry Accountant",
                "type": "string"
              },
              "ja": {
                "example": "経理入門",
                "type": "string"
              }
            },
            "type": "object"
          }
        },
        "type": "object"
      },
      "NextPeriodCorrectionContext": {
        "properties": {
          "data": {
            "properties": {
              "consumptionTaxQuarter": {
                "description": "A filed 消費税 quarter covering that date: the 期首修正 may still be posted there, with 不課税 / 対象外 lines only (BE ADR-0029 §5)",
                "nullable": true,
                "properties": {
                  "label": {
                    "nullable": true,
                    "type": "string"
                  },
                  "periodEnd": {
                    "type": "integer"
                  },
                  "periodStart": {
                    "type": "integer"
                  }
                },
                "type": "object"
              },
              "corrections": {
                "items": {
                  "properties": {
                    "amount": {
                      "type": "number"
                    },
                    "description": {
                      "nullable": true,
                      "type": "string"
                    },
                    "entryDate": {
                      "type": "integer"
                    },
                    "entryNumber": {
                      "type": "string"
                    },
                    "journalEntryId": {
                      "format": "uuid",
                      "type": "string"
                    },
                    "status": {
                      "type": "string"
                    }
                  },
                  "type": "object"
                },
                "type": "array"
              },
              "counterpartAccount": {
                "nullable": true,
                "properties": {
                  "code": {
                    "type": "string"
                  },
                  "name": {
                    "type": "string"
                  }
                },
                "type": "object"
              },
              "filedPeriod": {
                "properties": {
                  "end": {
                    "type": "integer"
                  },
                  "filingType": {
                    "type": "string"
                  },
                  "fiscalYear": {
                    "type": "integer"
                  },
                  "start": {
                    "type": "integer"
                  }
                },
                "type": "object"
              },
              "filedReturnId": {
                "format": "uuid",
                "type": "string"
              },
              "firstWritableDate": {
                "description": "The 期首 (first day of the next period) unless a corporate / annual filing locks it; YYYYMMDD",
                "nullable": true,
                "type": "integer"
              },
              "lockedRanges": {
                "items": {
                  "properties": {
                    "label": {
                      "nullable": true,
                      "type": "string"
                    },
                    "periodEnd": {
                      "type": "integer"
                    },
                    "periodStart": {
                      "type": "integer"
                    }
                  },
                  "type": "object"
                },
                "type": "array"
              },
              "nextPeriod": {
                "properties": {
                  "end": {
                    "type": "integer"
                  },
                  "name": {
                    "nullable": true,
                    "type": "string"
                  },
                  "start": {
                    "type": "integer"
                  }
                },
                "type": "object"
              }
            },
            "required": [
              "filedReturnId",
              "filedPeriod",
              "nextPeriod",
              "firstWritableDate",
              "corrections"
            ],
            "type": "object"
          },
          "success": {
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "NextPeriodCorrectionResult": {
        "properties": {
          "data": {
            "properties": {
              "description": {
                "type": "string"
              },
              "dryRun": {
                "type": "boolean"
              },
              "entryDate": {
                "type": "integer"
              },
              "entryNumber": {
                "type": "string"
              },
              "journalEntryId": {
                "format": "uuid",
                "nullable": true,
                "type": "string"
              },
              "lines": {
                "items": {
                  "properties": {
                    "accountCode": {
                      "type": "string"
                    },
                    "accountName": {
                      "type": "string"
                    },
                    "credit": {
                      "type": "number"
                    },
                    "debit": {
                      "type": "number"
                    },
                    "description": {
                      "type": "string"
                    },
                    "driftFindingId": {
                      "format": "uuid",
                      "nullable": true,
                      "type": "string"
                    },
                    "isCounterpart": {
                      "type": "boolean"
                    },
                    "taxCode": {
                      "description": "税区分: 4 不課税, 5 対象外, 1 / 2 課税, 3 非課税",
                      "type": "integer"
                    }
                  },
                  "type": "object"
                },
                "type": "array"
              },
              "nextPeriod": {
                "properties": {
                  "end": {
                    "type": "integer"
                  },
                  "start": {
                    "type": "integer"
                  }
                },
                "type": "object"
              },
              "total": {
                "type": "number"
              }
            },
            "required": [
              "entryNumber",
              "entryDate",
              "total",
              "lines",
              "journalEntryId",
              "dryRun"
            ],
            "type": "object"
          },
          "success": {
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "NoticeBulkStatusResponse": {
        "properties": {
          "data": {
            "properties": {
              "skippedIds": {
                "description": "Not the caller’s notice, or deleted — never touched",
                "items": {
                  "format": "uuid",
                  "type": "string"
                },
                "type": "array"
              },
              "status": {
                "enum": [
                  "unread",
                  "read",
                  "in_progress",
                  "completed",
                  "archived"
                ],
                "type": "string"
              },
              "unchangedIds": {
                "description": "Already in the requested status",
                "items": {
                  "format": "uuid",
                  "type": "string"
                },
                "type": "array"
              },
              "updated": {
                "description": "Notices whose status changed, with the status they had — what an undo restores",
                "items": {
                  "properties": {
                    "id": {
                      "format": "uuid",
                      "type": "string"
                    },
                    "previousStatus": {
                      "enum": [
                        "unread",
                        "read",
                        "in_progress",
                        "completed",
                        "archived"
                      ],
                      "type": "string"
                    }
                  },
                  "required": [
                    "id",
                    "previousStatus"
                  ],
                  "type": "object"
                },
                "type": "array"
              }
            },
            "required": [
              "status",
              "updated",
              "unchangedIds",
              "skippedIds"
            ],
            "type": "object"
          },
          "message": {
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "NoticeHistoryPoint": {
        "properties": {
          "amounts": {
            "additionalProperties": {
              "type": "number"
            },
            "description": "The numeric entries of the notice’s parsed CSV amounts, keyed as the CSV names them (健康保険料, 合計額, …). Which of them are money is the client’s rule; identifiers such as 事業所番号 are numeric too.",
            "example": {
              "健康保険料": 16524,
              "厚生年金保険料": 14028,
              "合計額": 30827,
              "子ども・子育て拠出金": 275
            },
            "type": "object"
          },
          "duplicateCount": {
            "description": "Other notices for the same period that were left out (the newest issuance is kept)",
            "type": "integer"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "noticeDate": {
            "example": "2026-08-18",
            "nullable": true,
            "type": "string"
          },
          "period": {
            "description": "西暦 year-month the notice is for",
            "example": "2026-07",
            "type": "string"
          }
        },
        "required": [
          "id",
          "period",
          "noticeDate",
          "amounts",
          "duplicateCount"
        ],
        "type": "object"
      },
      "NoticeHistoryResponse": {
        "properties": {
          "data": {
            "properties": {
              "comparable": {
                "description": "False when the notice has no parsed period or no issuer + kind — it is then never paired",
                "type": "boolean"
              },
              "months": {
                "example": 6,
                "maximum": 12,
                "minimum": 2,
                "type": "integer"
              },
              "period": {
                "example": "2026-07",
                "nullable": true,
                "type": "string"
              },
              "points": {
                "description": "One point per period present in the window, oldest first, this notice last",
                "items": {
                  "$ref": "#/components/schemas/NoticeHistoryPoint"
                },
                "type": "array"
              },
              "previous": {
                "description": "The same series exactly one period back; null = 前月データなし (never an older month)",
                "nullable": true,
                "properties": {
                  "amounts": {
                    "additionalProperties": {
                      "type": "number"
                    },
                    "description": "The numeric entries of the notice’s parsed CSV amounts, keyed as the CSV names them (健康保険料, 合計額, …). Which of them are money is the client’s rule; identifiers such as 事業所番号 are numeric too.",
                    "example": {
                      "健康保険料": 16524,
                      "厚生年金保険料": 14028,
                      "合計額": 30827,
                      "子ども・子育て拠出金": 275
                    },
                    "type": "object"
                  },
                  "duplicateCount": {
                    "description": "Other notices for the same period that were left out (the newest issuance is kept)",
                    "type": "integer"
                  },
                  "id": {
                    "format": "uuid",
                    "type": "string"
                  },
                  "noticeDate": {
                    "example": "2026-08-18",
                    "nullable": true,
                    "type": "string"
                  },
                  "period": {
                    "description": "西暦 year-month the notice is for",
                    "example": "2026-07",
                    "type": "string"
                  }
                },
                "required": [
                  "id",
                  "period",
                  "noticeDate",
                  "amounts",
                  "duplicateCount"
                ],
                "type": "object"
              },
              "reason": {
                "enum": [
                  "no_period",
                  "no_series",
                  null
                ],
                "nullable": true,
                "type": "string"
              }
            },
            "required": [
              "comparable",
              "reason",
              "period",
              "months",
              "previous",
              "points"
            ],
            "type": "object"
          },
          "message": {
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "Notification": {
        "properties": {
          "actions": {
            "description": "Available actions for the notification",
            "items": {
              "$ref": "#/components/schemas/NotificationAction"
            },
            "type": "array"
          },
          "category": {
            "$ref": "#/components/schemas/NotificationCategory"
          },
          "click_action": {
            "description": "Action taken when clicked",
            "example": "view_document",
            "nullable": true,
            "type": "string"
          },
          "clicked_at": {
            "description": "When notification was clicked",
            "example": null,
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "created_at": {
            "description": "Notification creation timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "data": {
            "description": "Additional notification data",
            "example": {
              "deadline": "2024-01-20",
              "documentType": "report"
            },
            "type": "object"
          },
          "delivery": {
            "$ref": "#/components/schemas/NotificationDelivery"
          },
          "dismissed_at": {
            "description": "When notification was dismissed",
            "example": null,
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "externalUrl": {
            "description": "External URL for navigation",
            "example": "https://external-system.com/document/123",
            "format": "uri",
            "nullable": true,
            "type": "string"
          },
          "id": {
            "description": "Notification unique identifier",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "is_clicked": {
            "description": "Whether notification has been clicked",
            "example": false,
            "type": "boolean"
          },
          "is_dismissed": {
            "description": "Whether notification has been dismissed",
            "example": false,
            "type": "boolean"
          },
          "is_read": {
            "description": "Whether notification has been read",
            "example": false,
            "type": "boolean"
          },
          "message": {
            "description": "Notification message content",
            "example": "Please review the quarterly report document.",
            "maxLength": 1000,
            "type": "string"
          },
          "priority": {
            "$ref": "#/components/schemas/NotificationPriority"
          },
          "read_at": {
            "description": "When notification was read",
            "example": "2024-01-15T10:35:00.000Z",
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "read_method": {
            "$ref": "#/components/schemas/ReadMethod"
          },
          "relatedIds": {
            "$ref": "#/components/schemas/NotificationRelatedIds"
          },
          "scheduling": {
            "$ref": "#/components/schemas/NotificationScheduling"
          },
          "sender": {
            "$ref": "#/components/schemas/NotificationSender"
          },
          "title": {
            "description": "Notification title",
            "example": "Document Review Required",
            "maxLength": 255,
            "type": "string"
          },
          "type": {
            "$ref": "#/components/schemas/NotificationType"
          },
          "updated_at": {
            "description": "Notification last update timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "url": {
            "description": "Internal URL for navigation",
            "example": "/documents/123",
            "nullable": true,
            "type": "string"
          },
          "user_id": {
            "description": "Recipient user ID",
            "example": "abc12345-def6-7890-ghij-klmnopqrstuv",
            "format": "uuid",
            "type": "string"
          }
        },
        "required": [
          "id",
          "type",
          "title",
          "message",
          "category",
          "priority",
          "user_id",
          "is_read",
          "is_clicked",
          "is_dismissed",
          "created_at",
          "updated_at"
        ],
        "type": "object"
      },
      "NotificationAction": {
        "properties": {
          "action": {
            "description": "Action identifier for handling",
            "example": "view_document",
            "type": "string"
          },
          "label": {
            "description": "Action button label",
            "example": "View Details",
            "type": "string"
          },
          "url": {
            "description": "URL to navigate when action is clicked",
            "example": "/documents/123",
            "format": "uri",
            "nullable": true,
            "type": "string"
          }
        },
        "required": [
          "label",
          "action"
        ],
        "type": "object"
      },
      "NotificationActionResponse": {
        "properties": {
          "data": {
            "properties": {
              "notificationId": {
                "format": "uuid",
                "type": "string"
              },
              "success": {
                "example": true,
                "type": "boolean"
              },
              "updatedAt": {
                "format": "date-time",
                "type": "string"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Notification marked as read successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "NotificationCategory": {
        "description": "Category of notification for organization and filtering",
        "enum": [
          "system",
          "message",
          "task",
          "friend",
          "document",
          "expense",
          "project",
          "travel"
        ],
        "example": "system",
        "type": "string"
      },
      "NotificationDelivery": {
        "properties": {
          "email": {
            "description": "Deliver via email",
            "example": false,
            "type": "boolean"
          },
          "push": {
            "description": "Deliver via push notification",
            "example": true,
            "type": "boolean"
          },
          "web": {
            "description": "Deliver via web interface",
            "example": true,
            "type": "boolean"
          }
        },
        "type": "object"
      },
      "NotificationListResponse": {
        "properties": {
          "data": {
            "properties": {
              "items": {
                "items": {
                  "$ref": "#/components/schemas/Notification"
                },
                "type": "array"
              },
              "pagination": {
                "$ref": "#/components/schemas/Pagination"
              },
              "unreadCount": {
                "example": 5,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Notifications retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "NotificationPriority": {
        "description": "Priority level for notification delivery and display",
        "enum": [
          "low",
          "medium",
          "high",
          "urgent"
        ],
        "example": "medium",
        "type": "string"
      },
      "NotificationRelatedIds": {
        "properties": {
          "clientId": {
            "description": "Related client ID",
            "example": "987e6543-f21a-43b5-c678-109876543210",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "documentId": {
            "description": "Related document ID",
            "example": "654e3210-a98b-76c5-d432-fedcba098765",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "expenseId": {
            "description": "Related expense ID",
            "example": "789e0123-e45b-67c8-d901-234567890123",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "projectId": {
            "description": "Related project ID",
            "example": "456e7890-f12a-34b5-c678-901234567890",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "taskId": {
            "description": "Related task ID",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          }
        },
        "type": "object"
      },
      "NotificationResponse": {
        "properties": {
          "data": {
            "properties": {
              "deliveryStatus": {
                "example": "queued",
                "type": "string"
              },
              "notificationId": {
                "format": "uuid",
                "type": "string"
              },
              "recipientCount": {
                "example": 3,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Notification created successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 201,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "NotificationScheduling": {
        "properties": {
          "expiresAt": {
            "description": "When the notification expires",
            "example": "2024-01-22T10:30:00.000Z",
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "scheduleAt": {
            "description": "When to deliver the notification",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "nullable": true,
            "type": "string"
          }
        },
        "type": "object"
      },
      "NotificationSender": {
        "properties": {
          "avatar": {
            "description": "Sender avatar image URL",
            "example": "https://example.com/avatar.jpg",
            "format": "uri",
            "nullable": true,
            "type": "string"
          },
          "email": {
            "description": "Sender email address",
            "example": "admin@company.com",
            "format": "email",
            "nullable": true,
            "type": "string"
          },
          "id": {
            "description": "Sender unique identifier",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "name": {
            "description": "Sender display name",
            "example": "System Administrator",
            "type": "string"
          }
        },
        "required": [
          "id",
          "name"
        ],
        "type": "object"
      },
      "NotificationType": {
        "description": "Type of notification for visual styling and behavior",
        "enum": [
          "success",
          "error",
          "warning",
          "info"
        ],
        "example": "info",
        "type": "string"
      },
      "OAuthCallbackRequest": {
        "properties": {
          "access_token": {
            "description": "OAuth access token received from Google",
            "example": "ya29.a0AfH6SMC...",
            "type": "string"
          },
          "expires_in": {
            "description": "Token expiration time in seconds",
            "example": 3600,
            "type": "number"
          },
          "refresh_token": {
            "description": "OAuth refresh token for token renewal",
            "example": "1//0GWThWrMpn5s2CgYIARAAGAwSNwF...",
            "type": "string"
          }
        },
        "required": [
          "access_token",
          "refresh_token",
          "expires_in"
        ],
        "type": "object"
      },
      "ObligationGuidance": {
        "properties": {
          "assetValues": {
            "description": "償却資産申告 only; null for other rules.",
            "nullable": true,
            "properties": {
              "assetYear": {
                "example": 2027,
                "type": "integer"
              },
              "countedCostYen": {
                "type": "integer"
              },
              "exemptionYen": {
                "example": 1500000,
                "type": "integer"
              },
              "items": {
                "items": {
                  "properties": {
                    "acquiredOn": {
                      "format": "date",
                      "type": "string"
                    },
                    "classLabel": {
                      "example": "建物附属設備",
                      "type": "string"
                    },
                    "costYen": {
                      "example": 990000,
                      "type": "integer"
                    },
                    "counted": {
                      "type": "boolean"
                    },
                    "location": {
                      "nullable": true,
                      "type": "string"
                    },
                    "name": {
                      "example": "ポンプ小屋保温",
                      "type": "string"
                    }
                  },
                  "required": [
                    "name",
                    "classLabel",
                    "acquiredOn",
                    "costYen",
                    "location",
                    "counted"
                  ],
                  "type": "object"
                },
                "type": "array"
              },
              "notes": {
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              "reviewCostYen": {
                "type": "integer"
              }
            },
            "required": [
              "assetYear",
              "items",
              "countedCostYen",
              "reviewCostYen",
              "exemptionYen",
              "notes"
            ],
            "type": "object"
          },
          "channels": {
            "items": {
              "properties": {
                "detail": {
                  "type": "string"
                },
                "key": {
                  "type": "string"
                },
                "label": {
                  "type": "string"
                }
              },
              "required": [
                "key",
                "label",
                "detail"
              ],
              "type": "object"
            },
            "type": "array"
          },
          "consequence": {
            "nullable": true,
            "type": "string"
          },
          "contentVersion": {
            "example": "2026-09-28.1",
            "nullable": true,
            "type": "string"
          },
          "deadlineId": {
            "format": "uuid",
            "type": "string"
          },
          "dueDate": {
            "format": "date",
            "type": "string"
          },
          "exemptions": {
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "filing": {
            "description": "Null while the obligation is open.",
            "nullable": true,
            "properties": {
              "completedAt": {
                "nullable": true,
                "type": "string"
              },
              "completionSource": {
                "description": "'manual' (the owner), 'engine' (a quarter the 消費税 schedule shows submitted) or 'register' (源泉 the 源泉徴収 register shows paid and bank-linked)",
                "nullable": true,
                "type": "string"
              },
              "evidenceFileId": {
                "format": "uuid",
                "nullable": true,
                "type": "string"
              },
              "evidenceFileName": {
                "nullable": true,
                "type": "string"
              },
              "filedMonth": {
                "description": "YYYY-MM (「7月頃」).",
                "example": "2026-07",
                "nullable": true,
                "type": "string"
              },
              "filedOn": {
                "description": "The owner’s date, or the e-Tax transmission day of an engine-completed 消費税 quarter.",
                "format": "date",
                "nullable": true,
                "type": "string"
              },
              "filedOnUnknown": {
                "description": "「提出日が不明」 — filedOn is null; filedMonth when known.",
                "type": "boolean"
              },
              "filingMethod": {
                "description": "提出方法; null on records made before it was asked.",
                "enum": [
                  "eltax",
                  "etax",
                  "mail",
                  "counter",
                  "other",
                  null
                ],
                "nullable": true,
                "type": "string"
              },
              "paidOn": {
                "description": "When 「納付しました」 closed a row that was filed first; filedOn stays the filing date.",
                "format": "date",
                "nullable": true,
                "type": "string"
              },
              "paymentPending": {
                "description": "Filed (「提出しました」) while the payment is still owed: the row stays open and reminds until 「納付しました」.",
                "type": "boolean"
              },
              "receiptNumber": {
                "nullable": true,
                "type": "string"
              },
              "trackingNumber": {
                "description": "簡易書留・特定記録の追跡番号 (郵送).",
                "nullable": true,
                "type": "string"
              },
              "undoable": {
                "type": "boolean"
              }
            },
            "required": [
              "filedOn",
              "filedOnUnknown",
              "filedMonth",
              "filingMethod",
              "receiptNumber",
              "trackingNumber",
              "evidenceFileId",
              "evidenceFileName",
              "completedAt",
              "completionSource",
              "undoable",
              "paymentPending",
              "paidOn"
            ],
            "type": "object"
          },
          "forms": {
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "periodLabel": {
            "example": "2026-santei",
            "type": "string"
          },
          "prep": {
            "description": "SBC's 目安 to start the work (not a legal date): the day of the rule's first prepare-stage reminder (p<n>) when it has one, else a fixed number of months before the due date.",
            "nullable": true,
            "properties": {
              "date": {
                "example": "2026-12-15",
                "format": "date",
                "type": "string"
              },
              "label": {
                "example": "Q3の帳簿を締める目安",
                "type": "string"
              }
            },
            "required": [
              "date",
              "label"
            ],
            "type": "object"
          },
          "professional": {
            "nullable": true,
            "properties": {
              "type": {
                "enum": [
                  "社労士",
                  "税理士",
                  "司法書士"
                ],
                "type": "string"
              },
              "when": {
                "type": "string"
              }
            },
            "required": [
              "type",
              "when"
            ],
            "type": "object"
          },
          "readOnly": {
            "description": "A row of the election / lock-in register (BE ADR-0023): いつから選べるか, nothing to file. 「提出しました」 and スキップ are refused with 409; 取り消す stays open.",
            "type": "boolean"
          },
          "ruleKey": {
            "example": "santei_kiso_filing",
            "type": "string"
          },
          "sources": {
            "items": {
              "$ref": "#/components/schemas/GuidanceSource"
            },
            "type": "array"
          },
          "status": {
            "enum": [
              "upcoming",
              "due_soon",
              "overdue",
              "completed",
              "not_applicable",
              "dismissed",
              "closed"
            ],
            "type": "string"
          },
          "steps": {
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "task": {
            "description": "The one thing to do, read from the row: what to file, where, because of what, within how long, and a condition to confirm first (when it does not hold, the task does not apply). Null when the row holds none.",
            "nullable": true,
            "properties": {
              "checkFirst": {
                "example": "代表者の住所だけの変更で異動届が要るか（都道府県税事務所・役場に確認）",
                "nullable": true,
                "type": "string"
              },
              "form": {
                "example": "異動届（代表者の住所の変更）",
                "nullable": true,
                "type": "string"
              },
              "submitTo": {
                "example": "東京都",
                "nullable": true,
                "type": "string"
              },
              "trigger": {
                "nullable": true,
                "properties": {
                  "date": {
                    "example": "2026-06-27",
                    "format": "date",
                    "nullable": true,
                    "type": "string"
                  },
                  "label": {
                    "example": "代表者の住所が変わった",
                    "type": "string"
                  }
                },
                "required": [
                  "label",
                  "date"
                ],
                "type": "object"
              },
              "window": {
                "example": "10日以内",
                "nullable": true,
                "type": "string"
              }
            },
            "required": [
              "form",
              "submitTo",
              "trigger",
              "window",
              "checkFirst"
            ],
            "type": "object"
          },
          "title": {
            "example": "算定基礎届",
            "type": "string"
          },
          "unverified": {
            "description": "Claims no primary source settled yet — shown as 確認中.",
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "what": {
            "nullable": true,
            "type": "string"
          },
          "whoMustFile": {
            "nullable": true,
            "type": "string"
          },
          "why": {
            "properties": {
              "facts": {
                "items": {
                  "$ref": "#/components/schemas/GuidanceFact"
                },
                "type": "array"
              },
              "line": {
                "type": "string"
              },
              "notes": {
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              "payments": {
                "description": "What to pay, per payee (interim taxes): the estimate from the prior filed return, the saved 納付書, the withdrawal that paid it and the usual route.",
                "items": {
                  "$ref": "#/components/schemas/GuidancePayment"
                },
                "type": "array"
              },
              "paymentsNote": {
                "description": "Sentences that apply to every payment, printed once.",
                "nullable": true,
                "type": "string"
              }
            },
            "required": [
              "line",
              "facts",
              "notes"
            ],
            "type": "object"
          },
          "withholdingValues": {
            "description": "源泉所得税 withheld in the months a 源泉 payment covers; null for other rules.",
            "nullable": true,
            "properties": {
              "label": {
                "example": "2026年1〜6月分",
                "type": "string"
              },
              "missingMonths": {
                "description": "Months with 役員報酬 on file but no record — the total may be short.",
                "items": {
                  "maximum": 12,
                  "minimum": 1,
                  "type": "integer"
                },
                "type": "array"
              },
              "notes": {
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              "rows": {
                "items": {
                  "properties": {
                    "gross": {
                      "example": 200000,
                      "nullable": true,
                      "type": "integer"
                    },
                    "note": {
                      "description": "Set when two records disagree.",
                      "nullable": true,
                      "type": "string"
                    },
                    "paidOn": {
                      "description": "納付日 from the 源泉徴収 register; null when not recorded as paid.",
                      "format": "date",
                      "nullable": true,
                      "type": "string"
                    },
                    "paymentDate": {
                      "format": "date",
                      "type": "string"
                    },
                    "source": {
                      "example": "源泉徴収の記録",
                      "type": "string"
                    },
                    "withheld": {
                      "example": 14000,
                      "nullable": true,
                      "type": "integer"
                    }
                  },
                  "required": [
                    "paymentDate",
                    "gross",
                    "withheld",
                    "source",
                    "note",
                    "paidOn"
                  ],
                  "type": "object"
                },
                "type": "array"
              },
              "total": {
                "nullable": true,
                "type": "integer"
              }
            },
            "required": [
              "label",
              "rows",
              "missingMonths",
              "total",
              "notes"
            ],
            "type": "object"
          },
          "yourValues": {
            "description": "The owner’s 4・5・6月 報酬 for 算定基礎届; null for other rules.",
            "nullable": true,
            "properties": {
              "average": {
                "description": "報酬月額 over the months with 17+ 支払基礎日数",
                "nullable": true,
                "type": "integer"
              },
              "notes": {
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              "rows": {
                "items": {
                  "properties": {
                    "amount": {
                      "example": 200000,
                      "nullable": true,
                      "type": "integer"
                    },
                    "basisDays": {
                      "example": 30,
                      "nullable": true,
                      "type": "integer"
                    },
                    "label": {
                      "example": "4月",
                      "type": "string"
                    },
                    "month": {
                      "enum": [
                        4,
                        5,
                        6
                      ],
                      "type": "integer"
                    },
                    "paymentDate": {
                      "format": "date",
                      "nullable": true,
                      "type": "string"
                    },
                    "source": {
                      "example": "給与明細（下書き）",
                      "type": "string"
                    }
                  },
                  "required": [
                    "month",
                    "label",
                    "paymentDate",
                    "amount",
                    "basisDays",
                    "source"
                  ],
                  "type": "object"
                },
                "type": "array"
              },
              "total": {
                "nullable": true,
                "type": "integer"
              },
              "year": {
                "example": 2026,
                "type": "integer"
              }
            },
            "required": [
              "year",
              "rows",
              "total",
              "average",
              "notes"
            ],
            "type": "object"
          }
        },
        "required": [
          "deadlineId",
          "ruleKey",
          "contentVersion",
          "status",
          "dueDate",
          "periodLabel",
          "title",
          "why",
          "exemptions",
          "channels",
          "steps",
          "forms",
          "sources",
          "unverified",
          "yourValues",
          "withholdingValues",
          "assetValues",
          "prep",
          "filing",
          "readOnly",
          "task"
        ],
        "type": "object"
      },
      "OfficerCompChecklistItem": {
        "properties": {
          "confirmWith": {
            "enum": [
              "税理士",
              "年金事務所"
            ],
            "nullable": true,
            "type": "string"
          },
          "detail": {
            "type": "string"
          },
          "dueDate": {
            "format": "date",
            "nullable": true,
            "type": "string"
          },
          "key": {
            "enum": [
              "mid_year_warning",
              "keep_paying",
              "tax_accountant",
              "resolution",
              "first_payday",
              "legal_limit",
              "social_insurance_loss",
              "shataku_transfer",
              "withholding_documents",
              "pre_filed_bonus"
            ],
            "type": "string"
          },
          "kind": {
            "enum": [
              "payroll",
              "resolution",
              "deadline",
              "social_insurance",
              "housing",
              "tax"
            ],
            "type": "string"
          },
          "needsTaxAccountant": {
            "description": "A judgement only a 税理士 can make (税理士確認)",
            "type": "boolean"
          },
          "reminderTitle": {
            "description": "Stable reminder title; null = not a reminder",
            "nullable": true,
            "type": "string"
          },
          "sources": {
            "items": {
              "$ref": "#/components/schemas/GuidanceSource"
            },
            "type": "array"
          },
          "title": {
            "type": "string"
          }
        },
        "required": [
          "key",
          "kind",
          "title",
          "detail",
          "dueDate",
          "needsTaxAccountant",
          "confirmWith",
          "reminderTitle",
          "sources"
        ],
        "type": "object"
      },
      "OfficerCompPlanReminder": {
        "properties": {
          "dueDate": {
            "format": "date",
            "type": "string"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "key": {
            "type": "string"
          },
          "result": {
            "description": "existing = already on file; moved = an open reminder with this title got the plan date",
            "enum": [
              "created",
              "moved",
              "existing"
            ],
            "type": "string"
          },
          "title": {
            "example": "役員報酬改定：今期最後の支給（月額は変えない）",
            "type": "string"
          }
        },
        "required": [
          "id",
          "key",
          "title",
          "dueDate",
          "result"
        ],
        "type": "object"
      },
      "OfficerCompensationPlan": {
        "properties": {
          "asOf": {
            "format": "date",
            "type": "string"
          },
          "checklist": {
            "items": {
              "$ref": "#/components/schemas/OfficerCompChecklistItem"
            },
            "type": "array"
          },
          "contentVersion": {
            "example": "2026-10-04.1",
            "type": "string"
          },
          "currentMonthlyAmount": {
            "example": 200000,
            "nullable": true,
            "type": "integer"
          },
          "currentMonthlySource": {
            "enum": [
              "schedule",
              "company_profile",
              "books"
            ],
            "nullable": true,
            "type": "string"
          },
          "fiscalYear": {
            "properties": {
              "end": {
                "format": "date",
                "type": "string"
              },
              "start": {
                "format": "date",
                "type": "string"
              }
            },
            "required": [
              "start",
              "end"
            ],
            "type": "object"
          },
          "lastPaydayAtCurrentAmount": {
            "format": "date",
            "nullable": true,
            "type": "string"
          },
          "nextWindow": {
            "properties": {
              "decideFrom": {
                "description": "Earliest day to decide the new amount",
                "example": "2027-02-16",
                "format": "date",
                "type": "string"
              },
              "firstPayday": {
                "description": "First payday at the new amount",
                "example": "2027-02-25",
                "format": "date",
                "nullable": true,
                "type": "string"
              },
              "legalLimit": {
                "description": "3月経過日 — last day a 改定 stays 定期同額",
                "example": "2027-05-15",
                "format": "date",
                "type": "string"
              }
            },
            "required": [
              "decideFrom",
              "firstPayday",
              "legalLimit"
            ],
            "type": "object"
          },
          "nonDeductibleIfChangedNow": {
            "description": "Estimated 損金不算入 if the amount changed at the next payday (mid_year only)",
            "example": 1600000,
            "nullable": true,
            "type": "integer"
          },
          "officerName": {
            "nullable": true,
            "type": "string"
          },
          "paid": {
            "description": "Months of this fiscal year with a positive NET 604 booking, up to today",
            "properties": {
              "amount": {
                "example": 1600000,
                "type": "integer"
              },
              "months": {
                "example": 8,
                "type": "integer"
              }
            },
            "required": [
              "months",
              "amount"
            ],
            "type": "object"
          },
          "payDay": {
            "example": 25,
            "nullable": true,
            "type": "integer"
          },
          "proposal": {
            "properties": {
              "annualCashSaving": {
                "nullable": true,
                "type": "integer"
              },
              "employerSocialInsuranceMonthly": {
                "nullable": true,
                "type": "integer"
              },
              "monthlyCashSaving": {
                "nullable": true,
                "type": "integer"
              },
              "monthlySaving": {
                "nullable": true,
                "type": "integer"
              },
              "newMonthlyAmount": {
                "example": 0,
                "type": "integer"
              },
              "note": {
                "type": "string"
              }
            },
            "required": [
              "newMonthlyAmount",
              "monthlySaving",
              "employerSocialInsuranceMonthly",
              "monthlyCashSaving",
              "annualCashSaving",
              "note"
            ],
            "type": "object"
          },
          "sources": {
            "items": {
              "$ref": "#/components/schemas/GuidanceSource"
            },
            "type": "array"
          },
          "status": {
            "enum": [
              "in_window",
              "mid_year",
              "no_compensation"
            ],
            "type": "string"
          },
          "statusMessage": {
            "description": "Plain Japanese status line",
            "type": "string"
          },
          "unverified": {
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "window": {
            "properties": {
              "decideFrom": {
                "description": "Earliest day to decide the new amount",
                "example": "2027-02-16",
                "format": "date",
                "type": "string"
              },
              "firstPayday": {
                "description": "First payday at the new amount",
                "example": "2027-02-25",
                "format": "date",
                "nullable": true,
                "type": "string"
              },
              "legalLimit": {
                "description": "3月経過日 — last day a 改定 stays 定期同額",
                "example": "2027-05-15",
                "format": "date",
                "type": "string"
              }
            },
            "required": [
              "decideFrom",
              "firstPayday",
              "legalLimit"
            ],
            "type": "object"
          }
        },
        "required": [
          "contentVersion",
          "asOf",
          "officerName",
          "fiscalYear",
          "currentMonthlyAmount",
          "currentMonthlySource",
          "payDay",
          "paid",
          "status",
          "statusMessage",
          "lastPaydayAtCurrentAmount",
          "nonDeductibleIfChangedNow",
          "window",
          "nextWindow",
          "proposal",
          "checklist",
          "unverified",
          "sources"
        ],
        "type": "object"
      },
      "OpenAIEmbeddingItem": {
        "properties": {
          "embedding": {
            "description": "Vector embedding for the text",
            "example": [
              0.1,
              -0.2,
              0.3,
              0.4
            ],
            "items": {
              "type": "number"
            },
            "type": "array"
          },
          "index": {
            "description": "Index of the input text this embedding corresponds to",
            "example": 0,
            "type": "integer"
          }
        },
        "required": [
          "embedding",
          "index"
        ],
        "type": "object"
      },
      "OpenAIEmbeddingRequest": {
        "properties": {
          "allowFallback": {
            "default": false,
            "description": "Allow fallback to system API key if user key fails",
            "example": true,
            "type": "boolean"
          },
          "dimensions": {
            "description": "Number of dimensions for the embedding vectors",
            "example": 1536,
            "maximum": 3072,
            "minimum": 1,
            "type": "integer"
          },
          "input": {
            "description": "Text or array of texts to generate embeddings for",
            "example": "The quick brown fox jumps over the lazy dog.",
            "oneOf": [
              {
                "type": "string"
              },
              {
                "items": {
                  "type": "string"
                },
                "type": "array"
              }
            ]
          },
          "model": {
            "default": "text-embedding-3-small",
            "description": "OpenAI embedding model to use",
            "example": "text-embedding-3-small",
            "type": "string"
          }
        },
        "required": [
          "input"
        ],
        "type": "object"
      },
      "OpenAIEmbeddingResponse": {
        "properties": {
          "data": {
            "properties": {
              "embeddings": {
                "description": "Array of generated embeddings",
                "items": {
                  "$ref": "#/components/schemas/OpenAIEmbeddingItem"
                },
                "type": "array"
              },
              "model": {
                "description": "Model used for embeddings",
                "example": "text-embedding-3-small",
                "type": "string"
              },
              "usage": {
                "properties": {
                  "promptTokens": {
                    "example": 25,
                    "type": "integer"
                  },
                  "totalTokens": {
                    "example": 25,
                    "type": "integer"
                  }
                },
                "required": [
                  "promptTokens",
                  "totalTokens"
                ],
                "type": "object"
              }
            },
            "required": [
              "embeddings",
              "usage",
              "model"
            ],
            "type": "object"
          },
          "message": {
            "example": "Embeddings generated successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "OpenAIImageAnalysisRequest": {
        "oneOf": [
          {
            "required": [
              "imageUrl"
            ]
          },
          {
            "required": [
              "imageBase64"
            ]
          }
        ],
        "properties": {
          "allowFallback": {
            "default": false,
            "description": "Allow fallback to system API key if user key fails",
            "example": true,
            "type": "boolean"
          },
          "detail": {
            "default": "auto",
            "description": "Level of detail for image analysis",
            "enum": [
              "low",
              "high",
              "auto"
            ],
            "example": "high",
            "type": "string"
          },
          "imageBase64": {
            "description": "Base64 encoded image data (alternative to imageUrl)",
            "example": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQ...",
            "type": "string"
          },
          "imageUrl": {
            "description": "URL of the image to analyze (alternative to imageBase64)",
            "example": "https://example.com/image.jpg",
            "format": "uri",
            "type": "string"
          },
          "maxTokens": {
            "description": "Maximum number of tokens in the response",
            "example": 300,
            "maximum": 4000,
            "minimum": 1,
            "type": "integer"
          },
          "model": {
            "default": "gpt-4-vision-preview",
            "description": "OpenAI vision model to use",
            "example": "gpt-4-vision-preview",
            "type": "string"
          },
          "prompt": {
            "description": "Prompt describing what to analyze in the image",
            "example": "Describe what you see in this image and identify any text.",
            "type": "string"
          }
        },
        "required": [
          "prompt"
        ],
        "type": "object"
      },
      "OpenAIImageAnalysisResponse": {
        "properties": {
          "data": {
            "properties": {
              "content": {
                "description": "Analysis result of the image",
                "example": "This image shows a modern office space with computers and people working...",
                "type": "string"
              },
              "extractedData": {
                "description": "Structured data extracted from the image",
                "example": {
                  "objects": [
                    "computer",
                    "desk",
                    "person"
                  ],
                  "text": "Welcome to our office"
                },
                "type": "object"
              },
              "finishReason": {
                "description": "Reason why analysis stopped",
                "example": "stop",
                "type": "string"
              },
              "model": {
                "description": "Model used for analysis",
                "example": "gpt-4-vision-preview",
                "type": "string"
              },
              "processingTime": {
                "description": "Time taken to process the image in milliseconds",
                "example": 2500,
                "type": "number"
              },
              "usage": {
                "$ref": "#/components/schemas/OpenAIUsage"
              }
            },
            "required": [
              "content",
              "usage",
              "model",
              "finishReason"
            ],
            "type": "object"
          },
          "message": {
            "example": "Image analyzed successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "OpenAIPreferences": {
        "properties": {
          "api_key": {
            "description": "API key for the AI provider (masked in responses)",
            "example": "****************",
            "format": "password",
            "type": "string"
          },
          "is_active": {
            "description": "Whether this AI provider is currently active",
            "example": true,
            "type": "boolean"
          },
          "model": {
            "description": "AI model identifier (e.g., gpt-4, gpt-3.5-turbo, claude-3-opus)",
            "example": "gpt-4",
            "type": "string"
          }
        },
        "type": "object"
      },
      "OpenAITextGenerationRequest": {
        "properties": {
          "allowFallback": {
            "default": false,
            "description": "Allow fallback to system API key if user key fails",
            "example": true,
            "type": "boolean"
          },
          "maxTokens": {
            "description": "Maximum number of tokens to generate",
            "example": 150,
            "maximum": 4000,
            "minimum": 1,
            "type": "integer"
          },
          "messages": {
            "description": "Array of conversation messages",
            "example": [
              {
                "content": "You are a helpful assistant.",
                "role": "system"
              },
              {
                "content": "Write a short poem about technology.",
                "role": "user"
              }
            ],
            "items": {
              "$ref": "#/components/schemas/Message"
            },
            "type": "array"
          },
          "model": {
            "default": "gpt-3.5-turbo",
            "description": "OpenAI model to use for generation",
            "example": "gpt-4",
            "type": "string"
          },
          "temperature": {
            "description": "Controls randomness in output (0 = deterministic, 2 = very random)",
            "example": 0.7,
            "maximum": 2,
            "minimum": 0,
            "type": "number"
          },
          "topP": {
            "description": "Controls diversity via nucleus sampling",
            "example": 0.9,
            "maximum": 1,
            "minimum": 0,
            "type": "number"
          }
        },
        "required": [
          "messages"
        ],
        "type": "object"
      },
      "OpenAITextGenerationResponse": {
        "properties": {
          "data": {
            "properties": {
              "content": {
                "description": "Generated text content",
                "example": "Technology flows like rivers through our digital age...",
                "type": "string"
              },
              "finishReason": {
                "description": "Reason why generation stopped",
                "example": "stop",
                "type": "string"
              },
              "model": {
                "description": "Model used for generation",
                "example": "gpt-4",
                "type": "string"
              },
              "usage": {
                "$ref": "#/components/schemas/OpenAIUsage"
              }
            },
            "required": [
              "content",
              "usage",
              "model",
              "finishReason"
            ],
            "type": "object"
          },
          "message": {
            "example": "Text generated successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "OpenAIUsage": {
        "properties": {
          "completionTokens": {
            "description": "Number of tokens in the completion",
            "example": 150,
            "type": "integer"
          },
          "promptTokens": {
            "description": "Number of tokens in the prompt",
            "example": 25,
            "type": "integer"
          },
          "totalTokens": {
            "description": "Total number of tokens used",
            "example": 175,
            "type": "integer"
          }
        },
        "required": [
          "promptTokens",
          "totalTokens"
        ],
        "type": "object"
      },
      "OpenAIUsageStatsResponse": {
        "properties": {
          "data": {
            "properties": {
              "lastUsedAt": {
                "description": "When the API was last used",
                "example": "2024-01-15T10:30:00.000Z",
                "format": "date-time",
                "nullable": true,
                "type": "string"
              },
              "monthlyUsage": {
                "properties": {
                  "cost": {
                    "description": "Estimated cost this month in USD",
                    "example": 2.5,
                    "type": "number"
                  },
                  "requests": {
                    "description": "Requests made this month",
                    "example": 50,
                    "type": "integer"
                  },
                  "tokens": {
                    "description": "Tokens used this month",
                    "example": 5000,
                    "type": "integer"
                  }
                },
                "required": [
                  "tokens",
                  "requests",
                  "cost"
                ],
                "type": "object"
              },
              "totalRequests": {
                "description": "Total number of API requests made",
                "example": 150,
                "type": "integer"
              },
              "totalTokensUsed": {
                "description": "Total tokens used by the user",
                "example": 15000,
                "type": "integer"
              }
            },
            "required": [
              "totalTokensUsed",
              "totalRequests",
              "lastUsedAt",
              "monthlyUsage"
            ],
            "type": "object"
          },
          "message": {
            "example": "Usage statistics retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "OpenQuestion": {
        "description": "未解決の会計・税務判断。書籍に載せた数値と、その根拠と、証憑を保持する。",
        "properties": {
          "answer": {
            "nullable": true,
            "type": "string"
          },
          "answeredAt": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "answeredBy": {
            "nullable": true,
            "type": "string"
          },
          "confirmedByProfessional": {
            "description": "税理士等が確認済み。true の間は自動検出で上書きされない。",
            "type": "boolean"
          },
          "detail": {
            "type": "string"
          },
          "domain": {
            "example": "consumption_tax",
            "nullable": true,
            "type": "string"
          },
          "engagementId": {
            "description": "この論点を載せている税理士等の依頼（確認事項管理表）",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "evidence": {
            "items": {
              "properties": {
                "id": {
                  "nullable": true,
                  "type": "string"
                },
                "kind": {
                  "enum": [
                    "file",
                    "agreement",
                    "journal_entry",
                    "url",
                    "statute",
                    "fixed_asset",
                    "account",
                    "bank_transaction",
                    "document"
                  ],
                  "type": "string"
                },
                "label": {
                  "type": "string"
                },
                "note": {
                  "nullable": true,
                  "type": "string"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "exchanges": {
            "description": "税理士とのやり取り（古い順）",
            "items": {
              "$ref": "#/components/schemas/OpenQuestionExchange"
            },
            "type": "array"
          },
          "findingKey": {
            "description": "起票元の指摘（`review:<id>` または整合性チェックの種類）",
            "nullable": true,
            "type": "string"
          },
          "fiscalYear": {
            "description": "この論点が決算確定・申告書を止める事業年度（開始年）。未設定なら依頼の年度（BE ADR-0031）",
            "nullable": true,
            "type": "integer"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "positionBasis": {
            "description": "その処理を選んだ理由",
            "nullable": true,
            "type": "string"
          },
          "questionKey": {
            "description": "同一論点の再提起が1行に集約されるための安定キー",
            "example": "agreement:26b9f627-…:surcharge-consumption-tax",
            "type": "string"
          },
          "raisedAt": {
            "format": "date-time",
            "type": "string"
          },
          "raisedBy": {
            "example": "system:finding-sync",
            "type": "string"
          },
          "reviewBy": {
            "description": "回答が依拠できなくなる期日（経過措置の失効等）",
            "format": "date",
            "nullable": true,
            "type": "string"
          },
          "severity": {
            "enum": [
              "blocking",
              "material",
              "advisory"
            ],
            "type": "string"
          },
          "sortOrder": {
            "description": "確認事項管理表での No.",
            "nullable": true,
            "type": "integer"
          },
          "status": {
            "enum": [
              "open",
              "answered",
              "confirmed",
              "superseded",
              "dismissed"
            ],
            "type": "string"
          },
          "title": {
            "example": "管理・共益費に対する消費税の取扱い（月額2,000円の差異）",
            "type": "string"
          },
          "workingPosition": {
            "description": "論点が未解決の間に採用している処理",
            "nullable": true,
            "type": "string"
          }
        },
        "required": [
          "id",
          "questionKey",
          "title",
          "status",
          "severity"
        ],
        "type": "object"
      },
      "OpenQuestionExchange": {
        "description": "確認事項のやり取り1件。税理士からの質問、または当社の回答。追記のみで編集・削除はしない。",
        "properties": {
          "at": {
            "format": "date-time",
            "type": "string"
          },
          "author": {
            "enum": [
              "professional",
              "company"
            ],
            "type": "string"
          },
          "body": {
            "type": "string"
          },
          "by": {
            "description": "記録したユーザーのID",
            "type": "string"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          }
        },
        "required": [
          "id",
          "author",
          "body",
          "at",
          "by"
        ],
        "type": "object"
      },
      "OpenQuestionImportPreview": {
        "properties": {
          "engagement": {
            "properties": {
              "displayName": {
                "type": "string"
              },
              "fiscalYear": {
                "nullable": true,
                "type": "integer"
              },
              "id": {
                "format": "uuid",
                "type": "string"
              }
            },
            "type": "object"
          },
          "fileHash": {
            "description": "SHA-256。取込（apply）で同じファイルであることの確認に使う",
            "type": "string"
          },
          "rows": {
            "items": {
              "$ref": "#/components/schemas/OpenQuestionImportRow"
            },
            "type": "array"
          },
          "sheetName": {
            "example": "管理シート",
            "type": "string"
          },
          "summary": {
            "properties": {
              "changed": {
                "type": "integer"
              },
              "conflict": {
                "type": "integer"
              },
              "matched": {
                "type": "integer"
              },
              "new": {
                "type": "integer"
              },
              "total": {
                "type": "integer"
              },
              "unchanged": {
                "type": "integer"
              }
            },
            "type": "object"
          }
        },
        "required": [
          "fileHash",
          "sheetName",
          "engagement",
          "rows",
          "summary"
        ],
        "type": "object"
      },
      "OpenQuestionImportRow": {
        "properties": {
          "addRounds": {
            "items": {
              "properties": {
                "author": {
                  "enum": [
                    "professional",
                    "company"
                  ],
                  "type": "string"
                },
                "body": {
                  "type": "string"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "conclusion": {
            "nullable": true,
            "properties": {
              "existing": {
                "nullable": true,
                "type": "string"
              },
              "incoming": {
                "type": "string"
              }
            },
            "type": "object"
          },
          "entryNumbers": {
            "description": "行に書かれた仕訳番号（証憑として紐付け）",
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "match": {
            "nullable": true,
            "properties": {
              "by": {
                "enum": [
                  "number",
                  "title"
                ],
                "type": "string"
              },
              "questionKey": {
                "type": "string"
              },
              "title": {
                "type": "string"
              }
            },
            "type": "object"
          },
          "no": {
            "nullable": true,
            "type": "integer"
          },
          "note": {
            "nullable": true,
            "type": "string"
          },
          "promotable": {
            "description": "最終結論がないときの税理士の最新回答",
            "nullable": true,
            "type": "string"
          },
          "recordedAnswer": {
            "description": "記録中の回答（最終結論として取り込む回答と違えば上書きの確認が必要）",
            "nullable": true,
            "type": "string"
          },
          "rowNumber": {
            "description": "シート上の行番号（確定・上書きの指定に使う）",
            "type": "integer"
          },
          "status": {
            "enum": [
              "new",
              "changed",
              "unchanged",
              "conflict"
            ],
            "type": "string"
          },
          "title": {
            "type": "string"
          }
        },
        "required": [
          "recordedAnswer",
          "rowNumber",
          "no",
          "title",
          "status",
          "match",
          "addRounds",
          "conclusion",
          "promotable",
          "note",
          "entryNumbers"
        ],
        "type": "object"
      },
      "OpenQuestionProfessionalAnswer": {
        "properties": {
          "conclusion": {
            "description": "記録された最終結論",
            "nullable": true,
            "type": "string"
          },
          "confirmedByProfessional": {
            "type": "boolean"
          },
          "fiscalYear": {
            "nullable": true,
            "type": "integer"
          },
          "latestProfessionalReply": {
            "nullable": true,
            "type": "string"
          },
          "questionKey": {
            "type": "string"
          },
          "sortOrder": {
            "nullable": true,
            "type": "integer"
          },
          "status": {
            "type": "string"
          },
          "targets": {
            "description": "この回答が関わる行（仕訳・固定資産・書類など）",
            "items": {
              "properties": {
                "id": {
                  "type": "string"
                },
                "kind": {
                  "type": "string"
                },
                "label": {
                  "type": "string"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "title": {
            "type": "string"
          }
        },
        "required": [
          "questionKey",
          "title",
          "status",
          "confirmedByProfessional",
          "latestProfessionalReply",
          "targets"
        ],
        "type": "object"
      },
      "OpeningBalanceImportLine": {
        "properties": {
          "accountName": {
            "type": "string"
          },
          "amount": {
            "minimum": 0,
            "type": "integer"
          },
          "isPlug": {
            "description": "true = 貸借差額から計算した繰越利益剰余金",
            "type": "boolean"
          },
          "rowNumbers": {
            "items": {
              "type": "integer"
            },
            "type": "array"
          },
          "sbcAccount": {
            "nullable": true,
            "properties": {
              "code": {
                "type": "string"
              },
              "id": {
                "type": "string"
              },
              "name": {
                "type": "string"
              }
            },
            "type": "object"
          },
          "side": {
            "enum": [
              "debit",
              "credit"
            ],
            "type": "string"
          },
          "subAccountNames": {
            "items": {
              "type": "string"
            },
            "type": "array"
          }
        },
        "required": [
          "accountName",
          "side",
          "amount",
          "isPlug"
        ],
        "type": "object"
      },
      "OpeningBalanceImportPreview": {
        "properties": {
          "balanced": {
            "type": "boolean"
          },
          "canImport": {
            "type": "boolean"
          },
          "creditTotal": {
            "description": "ファイルの貸方合計（差額計上前）",
            "type": "integer"
          },
          "debitTotal": {
            "description": "ファイルの借方合計（差額計上前）",
            "type": "integer"
          },
          "entryDate": {
            "description": "YYYYMMDD（期首日の前日）",
            "nullable": true,
            "type": "integer"
          },
          "entryDateSource": {
            "enum": [
              "request",
              "file",
              null
            ],
            "nullable": true,
            "type": "string"
          },
          "existingOpeningBalanceCount": {
            "type": "integer"
          },
          "format": {
            "enum": [
              "freee",
              "yayoi",
              "generic"
            ],
            "type": "string"
          },
          "lines": {
            "items": {
              "$ref": "#/components/schemas/OpeningBalanceImportLine"
            },
            "type": "array"
          },
          "plug": {
            "allOf": [
              {
                "$ref": "#/components/schemas/OpeningBalanceImportLine"
              }
            ],
            "description": "繰越利益剰余金の差額行（ファイルに繰越利益剰余金がなく、貸借が合わないときだけ）",
            "nullable": true
          },
          "rowErrors": {
            "items": {
              "$ref": "#/components/schemas/AccountingImportRowError"
            },
            "type": "array"
          },
          "unmappedAccounts": {
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "warnings": {
            "items": {
              "type": "string"
            },
            "type": "array"
          }
        },
        "required": [
          "format",
          "entryDate",
          "lines",
          "debitTotal",
          "creditTotal",
          "plug",
          "balanced",
          "unmappedAccounts",
          "canImport",
          "rowErrors",
          "warnings"
        ],
        "type": "object"
      },
      "OpeningBalanceImportResult": {
        "properties": {
          "creditTotal": {
            "type": "integer"
          },
          "debitTotal": {
            "type": "integer"
          },
          "entryDate": {
            "type": "integer"
          },
          "entryId": {
            "nullable": true,
            "type": "string"
          },
          "lineCount": {
            "type": "integer"
          },
          "plug": {
            "allOf": [
              {
                "$ref": "#/components/schemas/OpeningBalanceImportLine"
              }
            ],
            "nullable": true
          },
          "warnings": {
            "items": {
              "type": "string"
            },
            "type": "array"
          }
        },
        "required": [
          "entryDate",
          "lineCount",
          "debitTotal",
          "creditTotal",
          "warnings"
        ],
        "type": "object"
      },
      "OpeningBalanceLine": {
        "properties": {
          "account_id": {
            "description": "Account identifier for opening balance",
            "example": "456e7890-f12a-34b5-c678-901234567890",
            "format": "uuid",
            "type": "string"
          },
          "credit_amount": {
            "description": "Opening credit balance amount",
            "example": 0,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "debit_amount": {
            "description": "Opening debit balance amount",
            "example": 1000000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "description": {
            "description": "Line item description",
            "example": "期首残高 - 現金",
            "type": "string"
          }
        },
        "required": [
          "account_id",
          "debit_amount",
          "credit_amount"
        ],
        "type": "object"
      },
      "OpeningBalanceResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/JournalEntry"
          },
          "message": {
            "example": "Opening balance created successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 201,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "PLLineItem": {
        "properties": {
          "amount": {
            "description": "Current period amount in JPY",
            "example": 5000000,
            "format": "decimal",
            "type": "number"
          },
          "code": {
            "description": "Account code",
            "example": "4000",
            "type": "string"
          },
          "name": {
            "description": "Account name in English",
            "example": "Sales Revenue",
            "type": "string"
          },
          "nameJa": {
            "description": "Account name in Japanese",
            "example": "売上高",
            "type": "string"
          },
          "priorAmount": {
            "description": "Prior period amount in JPY",
            "example": 4500000,
            "format": "decimal",
            "nullable": true,
            "type": "number"
          },
          "variance": {
            "description": "Variance from prior period",
            "example": 500000,
            "format": "decimal",
            "nullable": true,
            "type": "number"
          },
          "variancePercent": {
            "description": "Variance percentage from prior period",
            "example": 11.11,
            "format": "decimal",
            "nullable": true,
            "type": "number"
          }
        },
        "required": [
          "code",
          "name",
          "nameJa",
          "amount"
        ],
        "type": "object"
      },
      "PLSection": {
        "properties": {
          "items": {
            "description": "Line items in this section",
            "items": {
              "$ref": "#/components/schemas/PLLineItem"
            },
            "type": "array"
          },
          "priorTotal": {
            "description": "Prior period section total",
            "example": 2300000,
            "format": "decimal",
            "nullable": true,
            "type": "number"
          },
          "title": {
            "description": "Section title in English",
            "example": "Operating Expenses",
            "type": "string"
          },
          "titleJa": {
            "description": "Section title in Japanese",
            "example": "販売費及び一般管理費",
            "type": "string"
          },
          "total": {
            "description": "Section total amount in JPY",
            "example": 2500000,
            "format": "decimal",
            "type": "number"
          }
        },
        "required": [
          "title",
          "titleJa",
          "items",
          "total"
        ],
        "type": "object"
      },
      "PaginatedActivityResponse": {
        "properties": {
          "activities": {
            "items": {
              "$ref": "#/components/schemas/UserActivity"
            },
            "type": "array"
          },
          "has_more": {
            "type": "boolean"
          },
          "limit": {
            "type": "integer"
          },
          "offset": {
            "type": "integer"
          },
          "total": {
            "type": "integer"
          }
        },
        "type": "object"
      },
      "Pagination": {
        "description": "Pagination envelope returned with every paginated list endpoint. Matches PaginationResponse<T>[\"pagination\"].",
        "properties": {
          "currentPage": {
            "description": "1-indexed page number",
            "minimum": 1,
            "type": "integer"
          },
          "hasNext": {
            "description": "True if a next page exists",
            "type": "boolean"
          },
          "hasPrevious": {
            "description": "True if a previous page exists",
            "type": "boolean"
          },
          "pageSize": {
            "description": "Items per page",
            "minimum": 1,
            "type": "integer"
          },
          "totalItems": {
            "description": "Total items across all pages",
            "minimum": 0,
            "type": "integer"
          },
          "totalPages": {
            "description": "Total number of pages",
            "minimum": 0,
            "type": "integer"
          }
        },
        "required": [
          "currentPage",
          "pageSize",
          "totalItems",
          "totalPages",
          "hasNext",
          "hasPrevious"
        ],
        "type": "object"
      },
      "PaginationMetadata": {
        "allOf": [
          {
            "$ref": "#/components/schemas/Pagination"
          }
        ]
      },
      "PaySlip": {
        "properties": {
          "created_at": {
            "description": "Pay slip creation timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "created_by": {
            "description": "User who created the pay slip",
            "example": "def67890-abc1-2345-6789-0123456789ab",
            "format": "uuid",
            "type": "string"
          },
          "document_id": {
            "description": "Associated document ID for pay slip storage",
            "example": "456e7890-f12a-34b5-c678-901234567890",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "employee_department": {
            "description": "Employee department (Japanese supported)",
            "example": "営業部",
            "maxLength": 255,
            "type": "string"
          },
          "employee_name": {
            "description": "Employee name (Japanese supported)",
            "example": "田中太郎",
            "maxLength": 255,
            "type": "string"
          },
          "gross_salary": {
            "description": "Gross salary amount in JPY",
            "example": 350000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "id": {
            "description": "Pay slip unique identifier",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "items": {
            "description": "Pay slip items (earnings and deductions)",
            "items": {
              "$ref": "#/components/schemas/PaySlipItem"
            },
            "type": "array"
          },
          "journal_entries_id": {
            "description": "Associated journal entries ID for accounting integration",
            "example": "789e0123-e45b-67c8-d901-234567890123",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "net_pay": {
            "description": "Net pay amount in JPY (gross - deductions)",
            "example": 265000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "pay_period_end": {
            "description": "Pay period end date in YYYYMMDD format",
            "example": 20240131,
            "maximum": 99991231,
            "minimum": 19700101,
            "type": "integer"
          },
          "pay_period_start": {
            "description": "Pay period start date in YYYYMMDD format",
            "example": 20240101,
            "maximum": 99991231,
            "minimum": 19700101,
            "type": "integer"
          },
          "payment_date": {
            "description": "Payment date in YYYYMMDD format",
            "example": 20240225,
            "maximum": 99991231,
            "minimum": 19700101,
            "nullable": true,
            "type": "integer"
          },
          "payment_type": {
            "$ref": "#/components/schemas/PaymentType",
            "description": "支払種別 (Payment Type) - salary, bonus, executive, fee, reimbursement, per_diem"
          },
          "payment_type_label": {
            "description": "Japanese label for payment type",
            "enum": [
              "給与",
              "賞与",
              "役員報酬",
              "報酬",
              "経費精算",
              "日当"
            ],
            "example": "給与",
            "type": "string"
          },
          "provision_note": {
            "description": "Additional provision notes",
            "example": "Overtime pay included for January",
            "maxLength": 1000,
            "nullable": true,
            "type": "string"
          },
          "status": {
            "$ref": "#/components/schemas/PaySlipStatus"
          },
          "total_deductions": {
            "description": "Total deductions amount in JPY",
            "example": 85000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "updated_at": {
            "description": "Pay slip last update timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "ytd_gross": {
            "description": "Year-to-date gross amount in JPY",
            "example": 1050000,
            "format": "decimal",
            "minimum": 0,
            "nullable": true,
            "type": "number"
          },
          "ytd_income_tax": {
            "description": "Year-to-date income tax amount in JPY",
            "example": 85000,
            "format": "decimal",
            "minimum": 0,
            "nullable": true,
            "type": "number"
          },
          "ytd_social_ins": {
            "description": "Year-to-date social insurance amount in JPY",
            "example": 150000,
            "format": "decimal",
            "minimum": 0,
            "nullable": true,
            "type": "number"
          },
          "ytd_taxable": {
            "description": "Year-to-date taxable amount in JPY",
            "example": 1000000,
            "format": "decimal",
            "minimum": 0,
            "nullable": true,
            "type": "number"
          }
        },
        "required": [
          "id",
          "employee_name",
          "employee_department",
          "pay_period_start",
          "pay_period_end",
          "status",
          "gross_salary",
          "total_deductions",
          "net_pay",
          "created_by",
          "created_at",
          "updated_at"
        ],
        "type": "object"
      },
      "PaySlipItem": {
        "properties": {
          "amount": {
            "description": "Item amount in JPY",
            "example": 250000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "id": {
            "description": "Pay slip item unique identifier",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "is_earning": {
            "description": "Whether this item is an earning (true) or deduction (false)",
            "example": true,
            "type": "boolean"
          },
          "item_name": {
            "description": "Pay slip item name (Japanese supported)",
            "example": "基本給",
            "maxLength": 255,
            "type": "string"
          },
          "notes": {
            "description": "Additional notes for the item",
            "example": "Monthly base salary",
            "maxLength": 500,
            "nullable": true,
            "type": "string"
          },
          "pay_slip_id": {
            "description": "Associated pay slip ID",
            "example": "abc12345-def6-7890-ghij-klmnopqrstuv",
            "format": "uuid",
            "type": "string"
          },
          "type": {
            "$ref": "#/components/schemas/PaySlipItemType"
          }
        },
        "required": [
          "id",
          "pay_slip_id",
          "type",
          "item_name",
          "amount",
          "is_earning"
        ],
        "type": "object"
      },
      "PaySlipItemType": {
        "description": "Pay slip item type for categorization",
        "example": 1,
        "minimum": 0,
        "type": "integer"
      },
      "PaySlipListResponse": {
        "properties": {
          "data": {
            "items": {
              "$ref": "#/components/schemas/PaySlip"
            },
            "type": "array"
          },
          "message": {
            "example": "Pay slips retrieved successfully",
            "type": "string"
          },
          "pagination": {
            "$ref": "#/components/schemas/Pagination"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "PaySlipResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/PaySlip"
          },
          "message": {
            "example": "Pay slip retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "PaySlipStatus": {
        "description": "Pay slip status for workflow management",
        "enum": [
          0,
          1,
          2,
          3
        ],
        "example": 1,
        "type": "integer",
        "x-enum-varnames": [
          "DRAFT",
          "ACTIVE",
          "PAID",
          "CANCELLED"
        ]
      },
      "PayeeBank": {
        "description": "The officer's own account (振込先) — never the company's",
        "nullable": true,
        "properties": {
          "holderName": {
            "nullable": true,
            "type": "string"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "label": {
            "type": "string"
          }
        },
        "type": "object"
      },
      "PayeeType": {
        "description": "Type of payee for withholding tax classification",
        "enum": [
          "individual",
          "corporation"
        ],
        "example": "individual",
        "type": "string"
      },
      "PaymentDocumentSummary": {
        "properties": {
          "attachmentCount": {
            "description": "Number of attached payment documents",
            "example": 3,
            "type": "integer"
          },
          "contentAmount": {
            "description": "VR-08 (v5.20+). The amount this 支払明細書's own content states, read in the dock's key\norder: `paymentInfo.amount` → `paymentInfo.totalAmount` → `paymentInfo.total_amount` →\n`settlementDetails.totalAmount` → `settlementDetails.total_amount` → `settlementDetails.amount`\n(container keys exist in camelCase and snake_case), else 0.\n\nThis is a DIFFERENT rule from `totalAmount`, which is computed from the linked expense rows, so the two\ncan disagree; the dock falls back to `contentAmount` only when `totalAmount` is 0. Before this field the\nclient fetched the whole document just to read it.",
            "example": 45000,
            "type": "number"
          },
          "currency": {
            "description": "Currency code",
            "example": "JPY",
            "type": "string"
          },
          "hasInkan": {
            "$ref": "#/components/schemas/DockHasInkan"
          },
          "id": {
            "description": "Payment document identifier",
            "example": "abc12345-def6-7890-ghij-klmnopqrstuv",
            "format": "uuid",
            "type": "string"
          },
          "linkedClaimsId": {
            "description": "ID of linked claims document",
            "example": "456e7890-f12a-34b5-c678-901234567890",
            "format": "uuid",
            "type": "string"
          },
          "name": {
            "description": "Payment document name",
            "example": "2024年1月支払通知書 - 営業部経費",
            "type": "string"
          },
          "status": {
            "description": "Document status",
            "enum": [
              "draft",
              "published",
              "archived"
            ],
            "example": "published",
            "type": "string"
          },
          "totalAmount": {
            "description": "Total payment amount",
            "example": 45000,
            "type": "number"
          },
          "type": {
            "description": "Document type (payment)",
            "example": "payment",
            "type": "string"
          }
        },
        "required": [
          "id",
          "name",
          "type",
          "totalAmount",
          "currency",
          "status",
          "attachmentCount"
        ],
        "type": "object"
      },
      "PaymentType": {
        "default": "salary",
        "description": "支払種別 (Payment Type) for categorizing pay slips.\n\n## Available Types\n- **salary** (給与): Regular monthly salary - 基本給, 月給\n- **bonus** (賞与): Seasonal bonus - 夏季賞与, 冬季賞与, 決算賞与\n- **executive** (役員報酬): Executive compensation - 取締役, 代表取締役, 監査役\n- **fee** (報酬): Professional fees - 講演料, 原稿料, 謝礼\n- **reimbursement** (経費精算): Expense reimbursement - 立替, 精算\n- **per_diem** (日当): Daily allowance - 出張手当, 宿泊手当\n\n## Usage\n- Auto-detected from item names and employee name if not explicitly set\n- Used for accurate withholding tax calculation (賞与 uses different rates)\n- Displayed as colored badges in document list UI",
        "enum": [
          "salary",
          "bonus",
          "executive",
          "fee",
          "reimbursement",
          "per_diem"
        ],
        "example": "salary",
        "type": "string",
        "x-enum-varnames": [
          "SALARY",
          "BONUS",
          "EXECUTIVE",
          "FEE",
          "REIMBURSEMENT",
          "PER_DIEM"
        ]
      },
      "PayoutClaim": {
        "properties": {
          "amount": {
            "description": "What the claim owes now",
            "type": "integer"
          },
          "displayTitle": {
            "description": "What the claim is for, derived from its content; the stored name is unchanged",
            "example": "高原拠点 · 消耗品費/会議費 21件",
            "nullable": true,
            "type": "string"
          },
          "documentDate": {
            "nullable": true,
            "type": "integer"
          },
          "documentId": {
            "format": "uuid",
            "type": "string"
          },
          "documentName": {
            "nullable": true,
            "type": "string"
          },
          "issuedAmount": {
            "description": "What the 支払明細書 printed for it",
            "nullable": true,
            "type": "integer"
          },
          "paid": {
            "type": "boolean"
          },
          "stale": {
            "description": "Amount changed after issue — settle refuses it until re-issued",
            "type": "boolean"
          },
          "transferIds": {
            "items": {
              "format": "uuid",
              "type": "string"
            },
            "type": "array"
          }
        },
        "type": "object"
      },
      "PayoutGroup": {
        "properties": {
          "claims": {
            "items": {
              "$ref": "#/components/schemas/PayoutClaim"
            },
            "type": "array"
          },
          "createdAt": {
            "nullable": true,
            "type": "string"
          },
          "documentName": {
            "nullable": true,
            "type": "string"
          },
          "paidAmount": {
            "type": "integer"
          },
          "payDate": {
            "example": "2026-08-25",
            "nullable": true,
            "type": "string"
          },
          "paymentDocumentId": {
            "format": "uuid",
            "type": "string"
          },
          "remainingAmount": {
            "type": "integer"
          },
          "status": {
            "enum": [
              "scheduled",
              "partially_paid",
              "paid"
            ],
            "type": "string"
          },
          "statusLabel": {
            "example": "振込予定",
            "type": "string"
          },
          "totalAmount": {
            "type": "integer"
          }
        },
        "type": "object"
      },
      "PayoutTransferCandidate": {
        "properties": {
          "amount": {
            "type": "integer"
          },
          "bankAccountId": {
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "confidence": {
            "type": "number"
          },
          "description": {
            "nullable": true,
            "type": "string"
          },
          "existingJournal": {
            "nullable": true,
            "properties": {
              "entryNumber": {
                "nullable": true,
                "type": "string"
              },
              "id": {
                "format": "uuid",
                "type": "string"
              }
            },
            "type": "object"
          },
          "fee": {
            "nullable": true,
            "properties": {
              "amount": {
                "type": "integer"
              },
              "description": {
                "nullable": true,
                "type": "string"
              },
              "hasJournal": {
                "type": "boolean"
              },
              "id": {
                "format": "uuid",
                "type": "string"
              },
              "transactionDate": {
                "nullable": true,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "payeeMatched": {
            "type": "boolean"
          },
          "proposedClaimIds": {
            "items": {
              "format": "uuid",
              "type": "string"
            },
            "nullable": true,
            "type": "array"
          },
          "reason": {
            "nullable": true,
            "type": "string"
          },
          "selectable": {
            "type": "boolean"
          },
          "transactionDate": {
            "nullable": true,
            "type": "integer"
          }
        },
        "type": "object"
      },
      "PerformanceTip": {
        "properties": {
          "description": {
            "description": "Detailed description of the tip",
            "example": "Fetch multiple tiles in one request to reduce latency",
            "type": "string"
          },
          "example": {
            "description": "Example implementation",
            "example": "POST /api/map/batch-tiles with array of tile coordinates",
            "type": "string"
          },
          "layers": {
            "description": "Applicable layers",
            "example": [
              "XKT002",
              "XKT006"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "status": {
            "description": "Implementation status",
            "example": "ACTIVE",
            "type": "string"
          },
          "tip": {
            "description": "Performance tip title",
            "example": "Use batch-tiles endpoint",
            "type": "string"
          },
          "ttl": {
            "description": "Cache TTL information",
            "example": "24 hours",
            "type": "string"
          }
        },
        "required": [
          "tip",
          "description"
        ],
        "type": "object"
      },
      "PerformanceTipsResponse": {
        "properties": {
          "data": {
            "properties": {
              "clientSide": {
                "description": "Client-side optimization tips",
                "items": {
                  "$ref": "#/components/schemas/PerformanceTip"
                },
                "type": "array"
              },
              "layerOptimization": {
                "additionalProperties": {
                  "type": "string"
                },
                "description": "Layer-specific optimization recommendations",
                "example": {
                  "Transactions (XPT001)": "Dynamic data - use clustering",
                  "Use Zones (XKT002)": "Static data - heavily cacheable"
                },
                "type": "object"
              },
              "serverSide": {
                "description": "Server-side optimization information",
                "items": {
                  "$ref": "#/components/schemas/PerformanceTip"
                },
                "type": "array"
              }
            },
            "type": "object"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "PrefectureGeo": {
        "properties": {
          "bounds": {
            "$ref": "#/components/schemas/Bounds",
            "description": "Prefecture geographic bounds"
          },
          "center": {
            "$ref": "#/components/schemas/Coordinates",
            "description": "Prefecture center coordinates"
          },
          "code": {
            "description": "Prefecture code (01-47)",
            "example": "13",
            "pattern": "^(0[1-9]|[1-4][0-7])$",
            "type": "string"
          },
          "defaultZoom": {
            "description": "Recommended zoom level for this prefecture",
            "example": 10,
            "maximum": 22,
            "minimum": 1,
            "type": "integer"
          },
          "name": {
            "description": "Prefecture name in Japanese",
            "example": "東京都",
            "type": "string"
          },
          "nameEn": {
            "description": "Prefecture name in English",
            "example": "Tokyo",
            "type": "string"
          }
        },
        "required": [
          "code",
          "name",
          "nameEn",
          "center",
          "bounds",
          "defaultZoom"
        ],
        "type": "object"
      },
      "PrefectureResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/PrefectureGeo"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "PrefecturesResponse": {
        "properties": {
          "data": {
            "properties": {
              "count": {
                "description": "Total number of prefectures",
                "example": 47,
                "type": "integer"
              },
              "prefectures": {
                "items": {
                  "$ref": "#/components/schemas/PrefectureGeo"
                },
                "type": "array"
              }
            },
            "type": "object"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "PrefetchRequest": {
        "properties": {
          "apiCode": {
            "$ref": "#/components/schemas/MLITGISAPICode"
          },
          "center": {
            "$ref": "#/components/schemas/TileRequest"
          },
          "radius": {
            "description": "Prefetch radius in tiles (maximum 2)",
            "example": 1,
            "maximum": 2,
            "minimum": 1,
            "type": "integer"
          }
        },
        "required": [
          "apiCode",
          "center"
        ],
        "type": "object"
      },
      "PrefetchResponse": {
        "properties": {
          "data": {
            "properties": {
              "alreadyCached": {
                "description": "Tiles already in cache",
                "example": 5,
                "type": "integer"
              },
              "prefetching": {
                "description": "Tiles being prefetched in background",
                "example": 4,
                "type": "integer"
              },
              "requested": {
                "description": "Total tiles requested for prefetch",
                "example": 9,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "PreflightResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/PreflightResult"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "PreflightResult": {
        "description": "Pre-filing integrity gate result for 消費税 XTX generation.",
        "properties": {
          "blockingCount": {
            "minimum": 0,
            "type": "integer"
          },
          "blockingViolations": {
            "items": {
              "$ref": "#/components/schemas/PreflightViolation"
            },
            "type": "array"
          },
          "passed": {
            "description": "True only when the engine evaluated the ledger AND found no blocking violations.",
            "type": "boolean"
          },
          "runEvaluated": {
            "description": "False when the integrity engine executed zero checks. An unevaluated ledger is not a clean ledger — clients must not render a green state.",
            "type": "boolean"
          },
          "vacuousReason": {
            "example": "no_checks_executed",
            "type": "string"
          },
          "violations": {
            "items": {
              "$ref": "#/components/schemas/PreflightViolation"
            },
            "type": "array"
          },
          "warningCount": {
            "minimum": 0,
            "type": "integer"
          }
        },
        "required": [
          "passed",
          "blockingCount",
          "warningCount",
          "runEvaluated",
          "violations"
        ],
        "type": "object"
      },
      "PreflightViolation": {
        "description": "One finding from the pre-filing integrity gate.",
        "properties": {
          "accountCode": {
            "type": [
              "string",
              "null"
            ]
          },
          "affectedIds": {
            "description": "IDs of the offending records when the check tracks them",
            "items": {
              "type": "string"
            },
            "type": [
              "array",
              "null"
            ]
          },
          "count": {
            "description": "Number of offending records",
            "minimum": 1,
            "type": "integer"
          },
          "details": {
            "description": "Explanation shown under the headline",
            "type": "string"
          },
          "fixUrl": {
            "description": "In-app deeplink that resolves the finding",
            "type": [
              "string",
              "null"
            ]
          },
          "name": {
            "description": "Headline rendered in the banner",
            "example": "課税区分の不一致",
            "type": "string"
          },
          "severity": {
            "description": "ERROR blocks XTX generation; WARNING is advisory. Uppercase by contract.",
            "enum": [
              "ERROR",
              "WARNING"
            ],
            "type": "string"
          },
          "type": {
            "description": "ViolationType, CT_SETTINGS_UNCONFIRMED, or PREFLIGHT_ENGINE_UNEVALUATED",
            "example": "CONSUMPTION_TAX_CLASSIFICATION",
            "type": "string"
          }
        },
        "required": [
          "type",
          "severity",
          "name",
          "details",
          "count"
        ],
        "type": "object"
      },
      "PreviewCalculationRequest": {
        "description": "Stateless 賃貸料相当額 preview payload — all fields match the validated DTO",
        "properties": {
          "building_legal_life_years": {
            "description": "法定耐用年数",
            "maximum": 100,
            "minimum": 1,
            "type": "integer"
          },
          "building_tax_base": {
            "description": "建物の固定資産税課税標準額 (JPY)",
            "nullable": true,
            "type": "number"
          },
          "is_multi_unit": {
            "description": "区分所有建物か否か",
            "type": "boolean"
          },
          "land_tax_base": {
            "description": "土地の固定資産税課税標準額 (JPY)",
            "nullable": true,
            "type": "number"
          },
          "monthly_rent_paid": {
            "description": "会社が家主に支払う月額賃料 (JPY)",
            "minimum": 0,
            "type": "integer"
          },
          "occupant_type": {
            "description": "役員 or 従業員",
            "enum": [
              "director",
              "employee"
            ],
            "type": "string"
          },
          "ownership": {
            "description": "社有 or 借上",
            "enum": [
              "owned",
              "leased"
            ],
            "type": "string"
          },
          "total_building_floor_area": {
            "description": "建物全体の床面積 (m²)",
            "minimum": 0,
            "type": "number"
          },
          "unit_floor_area": {
            "description": "専有面積 (m²)",
            "minimum": 0,
            "type": "number"
          },
          "use_fallback": {
            "description": "固定資産税評価額不明時のフォールバック計算を使用するか",
            "type": "boolean"
          }
        },
        "required": [
          "occupant_type",
          "ownership",
          "building_legal_life_years",
          "unit_floor_area",
          "total_building_floor_area",
          "monthly_rent_paid",
          "is_multi_unit",
          "use_fallback"
        ],
        "type": "object"
      },
      "PriceRange": {
        "properties": {
          "max": {
            "description": "Maximum estimated price",
            "example": 120000,
            "format": "decimal",
            "type": "number"
          },
          "min": {
            "description": "Minimum estimated price",
            "example": 80000,
            "format": "decimal",
            "type": "number"
          }
        },
        "required": [
          "min",
          "max"
        ],
        "type": "object"
      },
      "PricingTier": {
        "description": "Model pricing tier classification",
        "enum": [
          "economy",
          "standard",
          "premium"
        ],
        "example": "standard",
        "type": "string"
      },
      "Priority": {
        "description": "Priority level for actions or recommendations",
        "enum": [
          "high",
          "medium",
          "low"
        ],
        "example": "high",
        "type": "string"
      },
      "ProactiveInsight": {
        "properties": {
          "action": {
            "nullable": true,
            "properties": {
              "label": {
                "example": "確認する",
                "type": "string"
              },
              "target": {
                "example": "/expenses/new",
                "type": "string"
              },
              "type": {
                "enum": [
                  "navigate",
                  "dismiss",
                  "expand",
                  "confirm"
                ],
                "type": "string"
              },
              "variant": {
                "enum": [
                  "primary",
                  "secondary",
                  "ghost",
                  "destructive"
                ],
                "type": "string"
              }
            },
            "type": "object"
          },
          "deadline": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "expiresAt": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "message": {
            "example": "決算まであと30日です。30万円未満の備品購入は中小企業特例で即時経費にできます。",
            "type": "string"
          },
          "potentialValue": {
            "nullable": true,
            "properties": {
              "amount": {
                "example": 300000,
                "type": "number"
              },
              "formatted": {
                "example": "¥300,000",
                "type": "string"
              },
              "type": {
                "enum": [
                  "savings",
                  "cost",
                  "risk"
                ],
                "type": "string"
              }
            },
            "type": "object"
          },
          "priority": {
            "enum": [
              "urgent",
              "high",
              "medium",
              "low"
            ],
            "type": "string"
          },
          "relevantScreens": {
            "example": [
              "dashboard",
              "expense_wizard"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "status": {
            "enum": [
              "new",
              "viewed",
              "acted",
              "dismissed"
            ],
            "type": "string"
          },
          "title": {
            "example": "💰 今年度中の備品購入で即時経費OK",
            "type": "string"
          },
          "titlePlain": {
            "example": "今年度中の備品購入で即時経費OK",
            "type": "string"
          },
          "type": {
            "enum": [
              "tax_saving",
              "compliance_warning",
              "deadline",
              "optimization",
              "missing_document",
              "cash_flow_alert",
              "audit_risk",
              "rule_change",
              "achievement"
            ],
            "type": "string"
          }
        },
        "type": "object"
      },
      "ProblemDetails": {
        "description": "RFC 9457 Problem Details for HTTP APIs - standardized error response format",
        "properties": {
          "code": {
            "description": "Machine-readable error code from ErrorCode enum",
            "example": "ERR_3001",
            "type": "string"
          },
          "detail": {
            "description": "Detailed explanation of the error (may be localized)",
            "example": "入力内容が無効です",
            "type": "string"
          },
          "guidance": {
            "description": "User-facing guidance for error resolution (Japanese)",
            "example": "入力内容を確認してください",
            "type": "string"
          },
          "instance": {
            "description": "URI of the specific request that caused the error",
            "example": "/api/journals/123",
            "type": "string"
          },
          "message": {
            "description": "Human-readable error message (backward compat)",
            "example": "Invalid input",
            "type": "string"
          },
          "requestId": {
            "description": "Unique request trace ID for support tickets",
            "example": "req_abc123",
            "type": "string"
          },
          "retryable": {
            "description": "Whether the client should retry the request",
            "example": false,
            "type": "boolean"
          },
          "status": {
            "description": "HTTP status code",
            "example": 400,
            "type": "integer"
          },
          "success": {
            "description": "Always false for error responses (backward compat)",
            "example": false,
            "type": "boolean"
          },
          "title": {
            "description": "Short human-readable summary of the error",
            "example": "Invalid Input",
            "type": "string"
          },
          "type": {
            "description": "URI reference identifying the error type",
            "example": "https://api.soloboss.cloud/errors/ERR_3001",
            "format": "uri",
            "type": "string"
          }
        },
        "required": [
          "type",
          "title",
          "status",
          "detail",
          "code"
        ],
        "type": "object"
      },
      "ProblematicTransaction": {
        "properties": {
          "amount": {
            "description": "Transaction amount",
            "format": "decimal",
            "type": "number"
          },
          "createdAt": {
            "format": "date-time",
            "type": "string"
          },
          "description": {
            "description": "Transaction description",
            "type": "string"
          },
          "entryNumber": {
            "description": "Entry number",
            "example": "BNK-1768900801022",
            "type": "string"
          },
          "issueDescription": {
            "description": "Human-readable issue description",
            "type": "string"
          },
          "issueType": {
            "$ref": "#/components/schemas/IssueType"
          },
          "severity": {
            "$ref": "#/components/schemas/IssueSeverity"
          },
          "transactionId": {
            "description": "Transaction ID",
            "format": "uuid",
            "type": "string"
          },
          "transactionType": {
            "description": "Type of transaction",
            "example": "journal_entry",
            "type": "string"
          }
        },
        "required": [
          "transactionType",
          "transactionId",
          "entryNumber",
          "description",
          "amount",
          "issueType",
          "issueDescription",
          "severity",
          "createdAt"
        ],
        "type": "object"
      },
      "ProcessingRunResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/DemoProcessingRun"
          },
          "message": {
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "type": "object"
      },
      "ProcessingStatusEnum": {
        "description": "Processing status values for bank transactions",
        "enum": [
          "unprocessed",
          "journal_only",
          "doc_only",
          "complete",
          "no_doc_required",
          "fixed_asset",
          "fixed_asset_registered"
        ],
        "type": "string",
        "x-enum-descriptions": {
          "complete": "Has both journal entry AND linked documents",
          "doc_only": "No journal entry, has linked documents",
          "fixed_asset": "Transaction marked as fixed asset purchase (Step 2 - 固定資産購入 selected)",
          "fixed_asset_registered": "Asset registered in 固定資産台帳 (Step 3 completed)",
          "journal_only": "Has journal entry, no linked documents",
          "no_doc_required": "User explicitly marked as not requiring documents",
          "unprocessed": "No journal entry, no linked documents"
        }
      },
      "ProductEventBatch": {
        "properties": {
          "anonId": {
            "example": "6f1c2d3e-4b5a-4c6d-8e9f-0a1b2c3d4e5f",
            "pattern": "^[A-Za-z0-9_-]{8,64}$",
            "type": "string"
          },
          "events": {
            "items": {
              "$ref": "#/components/schemas/ProductEventInput"
            },
            "maxItems": 20,
            "minItems": 1,
            "type": "array"
          },
          "firstTouch": {
            "$ref": "#/components/schemas/ProductEventFirstTouch"
          },
          "sessionId": {
            "pattern": "^[A-Za-z0-9_-]{8,64}$",
            "type": "string"
          }
        },
        "required": [
          "events",
          "anonId"
        ],
        "type": "object"
      },
      "ProductEventFirstTouch": {
        "properties": {
          "landingPath": {
            "maxLength": 300,
            "type": "string"
          },
          "referrer": {
            "maxLength": 500,
            "type": "string"
          },
          "ts": {
            "format": "date-time",
            "type": "string"
          },
          "utmCampaign": {
            "maxLength": 100,
            "type": "string"
          },
          "utmContent": {
            "maxLength": 100,
            "type": "string"
          },
          "utmMedium": {
            "maxLength": 100,
            "type": "string"
          },
          "utmSource": {
            "maxLength": 100,
            "type": "string"
          }
        },
        "type": "object"
      },
      "ProductEventInput": {
        "properties": {
          "event": {
            "enum": [
              "landing_view",
              "why_view",
              "pricing_view",
              "signup_start",
              "demo_start",
              "deep_page_cta",
              "signup_view",
              "signup_method_chosen",
              "import_started",
              "share_created",
              "share_cta_clicked",
              "referral_link_created",
              "signup_source_answered"
            ],
            "example": "landing_view",
            "type": "string"
          },
          "occurredAt": {
            "format": "date-time",
            "type": "string"
          },
          "props": {
            "additionalProperties": {
              "oneOf": [
                {
                  "type": "string"
                },
                {
                  "type": "number"
                },
                {
                  "type": "boolean"
                },
                {
                  "type": "null"
                }
              ]
            },
            "description": "Flat string/number/boolean map, 1 KB max. No personal data.",
            "example": {
              "source": "hero"
            },
            "type": "object"
          }
        },
        "required": [
          "event"
        ],
        "type": "object"
      },
      "ProductRecommendation": {
        "properties": {
          "alternatives": {
            "description": "Alternative product suggestions",
            "example": [
              "デスクトップPC",
              "タブレット端末",
              "Chromebook"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "amazonSearchKeywords": {
            "description": "Suggested search keywords for finding the product",
            "example": [
              "ビジネスノートPC",
              "オフィス用パソコン",
              "Windows11"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "businessJustification": {
            "description": "Business justification for the purchase",
            "example": "業務効率化とデジタル化推進のため、従業員の作業環境改善に必要",
            "type": "string"
          },
          "category": {
            "description": "Product category",
            "example": "office_equipment",
            "type": "string"
          },
          "estimatedPrice": {
            "description": "Estimated purchase price",
            "example": 100000,
            "format": "decimal",
            "type": "number"
          },
          "id": {
            "description": "Unique recommendation identifier",
            "example": "rec_001",
            "type": "string"
          },
          "priceRange": {
            "$ref": "#/components/schemas/PriceRange"
          },
          "priority": {
            "$ref": "#/components/schemas/Priority"
          },
          "productName": {
            "description": "Recommended product name",
            "example": "ビジネス用ノートパソコン",
            "type": "string"
          },
          "relatedBusinessPurpose": {
            "description": "Related business purpose from company Teikan",
            "example": "システム開発および情報処理サービス業",
            "type": "string"
          },
          "riskExplanation": {
            "description": "Explanation of tax or compliance risks",
            "example": "業務用途の明確な証明が必要。私的使用との区別を明確にする必要があります。",
            "type": "string"
          },
          "riskLevel": {
            "$ref": "#/components/schemas/RiskLevel"
          },
          "taxTreatment": {
            "$ref": "#/components/schemas/TaxTreatment"
          }
        },
        "required": [
          "id",
          "productName",
          "category",
          "estimatedPrice",
          "priceRange",
          "businessJustification",
          "relatedBusinessPurpose",
          "taxTreatment",
          "riskLevel",
          "priority",
          "amazonSearchKeywords",
          "alternatives"
        ],
        "type": "object"
      },
      "ProfessionalEngagement": {
        "properties": {
          "contact_note": {
            "maxLength": 500,
            "nullable": true,
            "type": "string"
          },
          "created_at": {
            "format": "date-time",
            "type": "string"
          },
          "display_name": {
            "example": "顧問税理士 A先生",
            "maxLength": 150,
            "type": "string"
          },
          "engagement_how": {
            "description": "どう進めるか（手順・連絡手段）",
            "maxLength": 4000,
            "nullable": true,
            "type": "string"
          },
          "engagement_what": {
            "description": "何を依頼するのか（範囲・成果物）",
            "maxLength": 4000,
            "nullable": true,
            "type": "string"
          },
          "engagement_when": {
            "description": "いつ（時期・期限・面談予定）",
            "maxLength": 4000,
            "nullable": true,
            "type": "string"
          },
          "engagement_where": {
            "description": "どこで（面談形式・受け渡し）",
            "maxLength": 4000,
            "nullable": true,
            "type": "string"
          },
          "engagement_who": {
            "description": "誰に依頼するのか",
            "maxLength": 4000,
            "nullable": true,
            "type": "string"
          },
          "engagement_why": {
            "description": "なぜ依頼するのか（背景・論点）",
            "maxLength": 4000,
            "nullable": true,
            "type": "string"
          },
          "fiscal_year": {
            "description": "null = standing engagement (顧問契約)",
            "nullable": true,
            "type": "integer"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "notes": {
            "maxLength": 4000,
            "nullable": true,
            "type": "string"
          },
          "office_name": {
            "maxLength": 150,
            "nullable": true,
            "type": "string"
          },
          "professional_type": {
            "enum": [
              "TAX_ACCOUNTANT",
              "AUDITOR",
              "LAWYER",
              "JUDICIAL_SCRIVENER",
              "SOCIAL_INSURANCE",
              "OTHER"
            ],
            "type": "string"
          },
          "status": {
            "enum": [
              "considering",
              "requested",
              "engaged",
              "completed",
              "declined"
            ],
            "type": "string"
          },
          "updated_at": {
            "format": "date-time",
            "type": "string"
          }
        },
        "type": "object"
      },
      "ProfitLossStatement": {
        "properties": {
          "costOfSales": {
            "$ref": "#/components/schemas/PLSection"
          },
          "grossProfit": {
            "properties": {
              "amount": {
                "format": "decimal",
                "type": "number"
              },
              "margin": {
                "format": "decimal",
                "type": "number"
              },
              "priorAmount": {
                "format": "decimal",
                "nullable": true,
                "type": "number"
              }
            },
            "type": "object"
          },
          "netIncome": {
            "properties": {
              "amount": {
                "format": "decimal",
                "type": "number"
              },
              "margin": {
                "format": "decimal",
                "type": "number"
              },
              "priorAmount": {
                "format": "decimal",
                "nullable": true,
                "type": "number"
              }
            },
            "type": "object"
          },
          "operatingExpenses": {
            "$ref": "#/components/schemas/PLSection"
          },
          "operatingIncome": {
            "properties": {
              "amount": {
                "format": "decimal",
                "type": "number"
              },
              "margin": {
                "format": "decimal",
                "type": "number"
              },
              "priorAmount": {
                "format": "decimal",
                "nullable": true,
                "type": "number"
              }
            },
            "type": "object"
          },
          "ordinaryIncome": {
            "properties": {
              "amount": {
                "format": "decimal",
                "type": "number"
              },
              "margin": {
                "format": "decimal",
                "type": "number"
              },
              "priorAmount": {
                "format": "decimal",
                "nullable": true,
                "type": "number"
              }
            },
            "type": "object"
          },
          "period": {
            "properties": {
              "end": {
                "$ref": "#/components/schemas/DateFormat"
              },
              "fiscalYear": {
                "example": "2024年度",
                "type": "string"
              },
              "start": {
                "$ref": "#/components/schemas/DateFormat"
              }
            },
            "type": "object"
          },
          "priorPeriod": {
            "nullable": true,
            "properties": {
              "end": {
                "$ref": "#/components/schemas/DateFormat"
              },
              "start": {
                "$ref": "#/components/schemas/DateFormat"
              }
            },
            "type": "object"
          },
          "revenue": {
            "properties": {
              "otherIncome": {
                "items": {
                  "$ref": "#/components/schemas/PLLineItem"
                },
                "type": "array"
              },
              "priorTotal": {
                "format": "decimal",
                "nullable": true,
                "type": "number"
              },
              "sales": {
                "$ref": "#/components/schemas/PLLineItem"
              },
              "total": {
                "format": "decimal",
                "type": "number"
              }
            },
            "type": "object"
          }
        },
        "required": [
          "period",
          "revenue",
          "costOfSales",
          "grossProfit",
          "operatingExpenses",
          "operatingIncome",
          "ordinaryIncome",
          "netIncome"
        ],
        "type": "object"
      },
      "ProgressResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/EstablishmentProgress"
          },
          "success": {
            "example": true,
            "type": "boolean"
          },
          "timestamp": {
            "example": "2024-01-15T10:30:00Z",
            "format": "date-time",
            "type": "string"
          }
        },
        "required": [
          "success",
          "data",
          "timestamp"
        ],
        "type": "object"
      },
      "ProviderInfo": {
        "properties": {
          "description": {
            "description": "Provider description and model types",
            "example": "GPT-6 Sol / Luna / Astra + o-series reasoning",
            "type": "string"
          },
          "id": {
            "description": "Provider identifier",
            "example": "openai",
            "type": "string"
          },
          "models": {
            "description": "Available models for this provider",
            "items": {
              "$ref": "#/components/schemas/AIModel"
            },
            "type": "array"
          },
          "name": {
            "description": "Provider display name",
            "example": "OpenAI",
            "type": "string"
          },
          "requiresApiKey": {
            "description": "Whether provider requires API key",
            "example": true,
            "type": "boolean"
          },
          "supportsSystemKey": {
            "description": "Whether provider supports system-level API keys",
            "example": true,
            "type": "boolean"
          },
          "website": {
            "description": "Provider website URL",
            "example": "https://platform.openai.com",
            "format": "uri",
            "type": "string"
          }
        },
        "required": [
          "id",
          "name",
          "description",
          "website",
          "requiresApiKey",
          "supportsSystemKey",
          "models"
        ],
        "type": "object"
      },
      "ProviderModel": {
        "properties": {
          "created": {
            "description": "Unix timestamp of model creation (if available)",
            "example": 1706745600,
            "type": "number"
          },
          "description": {
            "description": "Model description or type (if available)",
            "example": "model",
            "type": "string"
          },
          "id": {
            "description": "Unique model identifier from the provider",
            "example": "gpt-4o",
            "type": "string"
          },
          "name": {
            "description": "Human-readable model name",
            "example": "gpt-4o",
            "type": "string"
          },
          "ownedBy": {
            "description": "Organization that owns the model (OpenAI-specific)",
            "example": "openai",
            "type": "string"
          }
        },
        "required": [
          "id",
          "name"
        ],
        "type": "object"
      },
      "ProviderModelsResponse": {
        "properties": {
          "data": {
            "properties": {
              "defaultModel": {
                "description": "Default model ID for this provider",
                "example": "gpt-6-sol",
                "type": "string"
              },
              "models": {
                "description": "Models available for this provider",
                "items": {
                  "$ref": "#/components/schemas/AIModel"
                },
                "type": "array"
              },
              "provider": {
                "description": "Provider identifier",
                "example": "openai",
                "type": "string"
              }
            },
            "required": [
              "provider",
              "models",
              "defaultModel"
            ],
            "type": "object"
          },
          "message": {
            "example": "Models for openai retrieved successfully",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ProviderModelsResult": {
        "properties": {
          "error": {
            "description": "Error message if the provider fetch failed (provider is still included with empty models)",
            "example": "GEMINI_API_KEY not configured",
            "type": "string"
          },
          "fetchedAt": {
            "description": "ISO timestamp of when models were fetched",
            "example": "2026-03-11T12:00:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "models": {
            "description": "Live model list from the provider",
            "items": {
              "$ref": "#/components/schemas/ProviderModel"
            },
            "type": "array"
          },
          "provider": {
            "description": "Provider identifier",
            "enum": [
              "openai",
              "anthropic",
              "vertex"
            ],
            "example": "openai",
            "type": "string"
          },
          "totalModels": {
            "description": "Total number of models returned",
            "example": 42,
            "type": "integer"
          }
        },
        "required": [
          "provider",
          "models",
          "totalModels",
          "fetchedAt"
        ],
        "type": "object"
      },
      "ProviderNotFoundResponse": {
        "properties": {
          "data": {
            "example": null,
            "type": "null"
          },
          "message": {
            "example": "Provider 'invalid-provider' not found or has no models",
            "type": "string"
          },
          "success": {
            "example": false,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ProviderWithModels": {
        "properties": {
          "models": {
            "items": {
              "properties": {
                "model_display_name": {
                  "description": "User-friendly model name",
                  "example": "GPT-4o",
                  "type": "string"
                },
                "model_name": {
                  "description": "Technical model identifier",
                  "example": "gpt-4o",
                  "type": "string"
                },
                "provider": {
                  "description": "Provider ID from AIProvider enum",
                  "example": 0,
                  "type": "number"
                }
              },
              "required": [
                "provider",
                "model_name",
                "model_display_name"
              ],
              "type": "object"
            },
            "type": "array"
          },
          "provider": {
            "description": "Provider name",
            "example": "OpenAI",
            "type": "string"
          }
        },
        "required": [
          "provider",
          "models"
        ],
        "type": "object"
      },
      "ProvidersResponse": {
        "properties": {
          "data": {
            "example": [
              "OpenAI",
              "Anthropic",
              "Google",
              "Together",
              "OpenRouter"
            ],
            "items": {
              "description": "Provider name",
              "type": "string"
            },
            "type": "array"
          },
          "message": {
            "example": "AI providers retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ProvisionPublicDemoRequest": {
        "properties": {
          "source": {
            "example": "landing-page",
            "type": "string"
          }
        },
        "type": "object"
      },
      "PublicDemoEnvelope": {
        "properties": {
          "data": {
            "type": "object"
          },
          "success": {
            "type": "boolean"
          }
        },
        "type": "object"
      },
      "PublicDocumentShareResolve": {
        "description": "Sanitized document payload for a valid share token",
        "type": "object"
      },
      "PurchaseRecommendationRequest": {
        "properties": {
          "budgetLimit": {
            "$ref": "#/components/schemas/BudgetLimit"
          },
          "companyId": {
            "description": "Company ID for recommendations",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "productCategories": {
            "description": "Specific product categories to focus on (optional)",
            "example": [
              "office_equipment",
              "software",
              "furniture"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          }
        },
        "required": [
          "companyId",
          "budgetLimit"
        ],
        "type": "object"
      },
      "PurchaseRecommendationResponse": {
        "properties": {
          "disclaimer": {
            "description": "Important disclaimer about recommendations",
            "example": "これらの推奨事項は一般的な情報提供を目的としており、個別の税務アドバイスではありません。実際の購入前に税理士にご相談ください。",
            "type": "string"
          },
          "recommendations": {
            "description": "List of product recommendations",
            "items": {
              "$ref": "#/components/schemas/ProductRecommendation"
            },
            "type": "array"
          },
          "summary": {
            "$ref": "#/components/schemas/PurchaseRecommendationSummary"
          }
        },
        "required": [
          "recommendations",
          "summary",
          "disclaimer"
        ],
        "type": "object"
      },
      "PurchaseRecommendationSummary": {
        "properties": {
          "potentialTaxSavings": {
            "description": "Potential tax savings from recommendations",
            "example": 225000,
            "format": "decimal",
            "type": "number"
          },
          "riskAssessment": {
            "description": "Overall risk assessment",
            "example": "適切な証憑保存と業務用途の明確化により、税務リスクは低く抑えられます",
            "type": "string"
          },
          "totalEstimatedCost": {
            "description": "Total estimated cost of all recommendations",
            "example": 750000,
            "format": "decimal",
            "type": "number"
          },
          "totalRecommendations": {
            "description": "Total number of recommendations",
            "example": 8,
            "type": "integer"
          }
        },
        "required": [
          "totalRecommendations",
          "totalEstimatedCost",
          "potentialTaxSavings",
          "riskAssessment"
        ],
        "type": "object"
      },
      "PurchaseRecommendationsResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/PurchaseRecommendationResponse"
          },
          "message": {
            "example": "Purchase recommendations retrieved",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "PushSubscribeRequest": {
        "properties": {
          "deviceInfo": {
            "$ref": "#/components/schemas/DeviceInfo"
          },
          "subscription": {
            "$ref": "#/components/schemas/PushSubscription"
          }
        },
        "required": [
          "subscription"
        ],
        "type": "object"
      },
      "PushSubscription": {
        "properties": {
          "endpoint": {
            "description": "Push service endpoint URL",
            "example": "https://fcm.googleapis.com/fcm/send/abc123",
            "format": "uri",
            "type": "string"
          },
          "keys": {
            "properties": {
              "auth": {
                "description": "Authentication secret",
                "example": "tBHItJI5svbpez7KI4CCXg",
                "type": "string"
              },
              "p256dh": {
                "description": "Public key for encryption",
                "example": "BEl62iUYgUivxIkv69yViEuiBIa-Ib9-SkvMeAtA3LFw",
                "type": "string"
              }
            },
            "required": [
              "p256dh",
              "auth"
            ],
            "type": "object"
          }
        },
        "required": [
          "endpoint",
          "keys"
        ],
        "type": "object"
      },
      "PushSubscriptionResponse": {
        "properties": {
          "data": {
            "properties": {
              "subscriptionId": {
                "description": "Unique subscription identifier",
                "example": "123e4567-e89b-12d3-a456-426614174000",
                "format": "uuid",
                "type": "string"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Successfully subscribed to push notifications",
            "type": "string"
          },
          "statusCode": {
            "example": 201,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "QualifiedInvoiceData": {
        "properties": {
          "bankInfo": {
            "nullable": true,
            "properties": {
              "accountHolder": {
                "type": "string"
              },
              "accountNumber": {
                "type": "string"
              },
              "accountType": {
                "type": "string"
              },
              "bankName": {
                "type": "string"
              },
              "branchName": {
                "type": "string"
              }
            },
            "type": "object"
          },
          "dueDate": {
            "description": "Payment due date (支払期限)",
            "example": "2024-04-15",
            "format": "date",
            "nullable": true,
            "type": "string"
          },
          "grandTotal": {
            "description": "Grand total including tax (税込合計)",
            "example": 550000,
            "format": "decimal",
            "type": "number"
          },
          "invoiceNumber": {
            "description": "Generated invoice number",
            "example": "INV-202403-0001",
            "type": "string"
          },
          "isRecipientVerified": {
            "description": "Whether recipient registration number was verified",
            "example": true,
            "type": "boolean"
          },
          "issueDate": {
            "description": "Invoice issue date (発行年月日)",
            "example": "2024-03-15",
            "format": "date",
            "type": "string"
          },
          "issuer": {
            "$ref": "#/components/schemas/QualifiedInvoiceIssuer"
          },
          "items": {
            "description": "Processed invoice items",
            "items": {
              "$ref": "#/components/schemas/QualifiedInvoiceProcessedItem"
            },
            "type": "array"
          },
          "notes": {
            "description": "Additional notes",
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "recipient": {
            "$ref": "#/components/schemas/QualifiedInvoiceRecipient"
          },
          "subtotal": {
            "description": "Total excluding tax (税抜合計)",
            "example": 500000,
            "format": "decimal",
            "type": "number"
          },
          "taxSummary": {
            "description": "Tax summary by rate (税率別集計)",
            "items": {
              "$ref": "#/components/schemas/TaxSummary"
            },
            "type": "array"
          },
          "totalTax": {
            "description": "Total tax amount (消費税合計)",
            "example": 50000,
            "format": "decimal",
            "type": "number"
          },
          "transactionDate": {
            "description": "Transaction date (取引年月日)",
            "example": "2024-03-15",
            "format": "date",
            "type": "string"
          },
          "verificationDate": {
            "description": "Verification timestamp",
            "example": "2024-03-15T10:30:00.000Z",
            "format": "date-time",
            "nullable": true,
            "type": "string"
          }
        },
        "required": [
          "invoiceNumber",
          "issuer",
          "recipient",
          "transactionDate",
          "issueDate",
          "items",
          "taxSummary",
          "subtotal",
          "totalTax",
          "grandTotal",
          "notes",
          "isRecipientVerified"
        ],
        "type": "object"
      },
      "QualifiedInvoiceGetResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/QualifiedInvoiceData"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "QualifiedInvoiceHealthResponse": {
        "properties": {
          "features": {
            "example": [
              "Generate qualified invoices (適格請求書)",
              "Auto-insert registration number",
              "Multi-tax rate support (10%/8%)",
              "Recipient verification",
              "HTML generation for PDF export"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "message": {
            "example": "適格請求書 API is running",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "features"
        ],
        "type": "object"
      },
      "QualifiedInvoiceIssuer": {
        "properties": {
          "address": {
            "description": "Issuer address (発行事業者住所)",
            "example": "東京都新宿区1-1-1",
            "type": "string"
          },
          "email": {
            "description": "Email address (メールアドレス)",
            "example": "info@sample.co.jp",
            "format": "email",
            "nullable": true,
            "type": "string"
          },
          "name": {
            "description": "Issuer company name (発行事業者名)",
            "example": "株式会社サンプル",
            "type": "string"
          },
          "phone": {
            "description": "Phone number (電話番号)",
            "example": "03-1234-5678",
            "nullable": true,
            "type": "string"
          },
          "registrationNumber": {
            "description": "Issuer registration number (適格請求書発行事業者登録番号)",
            "example": "T1234567890123",
            "type": "string"
          }
        },
        "required": [
          "registrationNumber",
          "name",
          "address"
        ],
        "type": "object"
      },
      "QualifiedInvoiceItem": {
        "properties": {
          "amount": {
            "description": "Total amount excluding tax (金額・税抜)",
            "example": 500000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "description": {
            "description": "Item description (品目)",
            "example": "Webサイト制作業務",
            "type": "string"
          },
          "quantity": {
            "description": "Item quantity (数量)",
            "example": 1,
            "minimum": 0,
            "type": "number"
          },
          "tax_rate_category": {
            "$ref": "#/components/schemas/TaxRateCategory"
          },
          "unit": {
            "default": "式",
            "description": "Unit of measurement (単位)",
            "example": "式",
            "type": "string"
          },
          "unit_price": {
            "description": "Unit price excluding tax (単価・税抜)",
            "example": 500000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          }
        },
        "required": [
          "description",
          "unit_price",
          "tax_rate_category"
        ],
        "type": "object"
      },
      "QualifiedInvoicePreviewResponse": {
        "properties": {
          "data": {
            "properties": {
              "html": {
                "description": "Generated HTML for preview",
                "example": "<!DOCTYPE html><html lang=\"ja\">...",
                "type": "string"
              },
              "invoice": {
                "$ref": "#/components/schemas/QualifiedInvoiceData"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "プレビュー用適格請求書を生成しました",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "QualifiedInvoiceProcessedItem": {
        "properties": {
          "amount": {
            "description": "Total amount excluding tax",
            "example": 500000,
            "format": "decimal",
            "type": "number"
          },
          "description": {
            "description": "Item description",
            "example": "Webサイト制作業務",
            "type": "string"
          },
          "lineNumber": {
            "description": "Line number in invoice",
            "example": 1,
            "type": "integer"
          },
          "quantity": {
            "description": "Item quantity",
            "example": 1,
            "type": "number"
          },
          "taxRate": {
            "description": "Tax rate percentage",
            "example": 10,
            "type": "number"
          },
          "taxRateCategory": {
            "$ref": "#/components/schemas/TaxRateCategory"
          },
          "unit": {
            "description": "Unit of measurement",
            "example": "式",
            "type": "string"
          },
          "unitPrice": {
            "description": "Unit price excluding tax",
            "example": 500000,
            "format": "decimal",
            "type": "number"
          }
        },
        "required": [
          "lineNumber",
          "description",
          "quantity",
          "unit",
          "unitPrice",
          "taxRateCategory",
          "taxRate",
          "amount"
        ],
        "type": "object"
      },
      "QualifiedInvoiceRecipient": {
        "properties": {
          "address": {
            "description": "Recipient address (受領事業者住所)",
            "example": "東京都渋谷区1-1-1",
            "nullable": true,
            "type": "string"
          },
          "name": {
            "description": "Recipient name (受領事業者名)",
            "example": "株式会社クライアント",
            "type": "string"
          },
          "registrationNumber": {
            "description": "Recipient registration number (受領事業者登録番号)",
            "example": "T9876543210987",
            "nullable": true,
            "type": "string"
          }
        },
        "required": [
          "name"
        ],
        "type": "object"
      },
      "QualifiedInvoiceResponse": {
        "properties": {
          "data": {
            "properties": {
              "invoice": {
                "$ref": "#/components/schemas/QualifiedInvoiceData"
              },
              "invoiceNumber": {
                "description": "Generated invoice number",
                "example": "INV-202403-0001",
                "type": "string"
              },
              "savedId": {
                "description": "Saved invoice ID (if saved to database)",
                "example": "123e4567-e89b-12d3-a456-426614174000",
                "format": "uuid",
                "nullable": true,
                "type": "string"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "適格請求書を生成しました",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "QuarterlySummary": {
        "properties": {
          "estimatedTaxDue": {
            "description": "Estimated tax due for quarter",
            "example": 27500,
            "format": "decimal",
            "type": "number"
          },
          "periodEnd": {
            "description": "Quarter end date",
            "example": "2024-03-31",
            "format": "date",
            "type": "string"
          },
          "periodStart": {
            "description": "Quarter start date",
            "example": "2024-01-01",
            "format": "date",
            "type": "string"
          },
          "purchaseTax": {
            "description": "Total purchase tax for quarter",
            "example": 82500,
            "format": "decimal",
            "type": "number"
          },
          "quarter": {
            "description": "Quarter number",
            "example": 1,
            "maximum": 4,
            "minimum": 1,
            "type": "integer"
          },
          "salesTax": {
            "description": "Total sales tax for quarter",
            "example": 137500,
            "format": "decimal",
            "type": "number"
          }
        },
        "required": [
          "quarter",
          "periodStart",
          "periodEnd",
          "salesTax",
          "purchaseTax",
          "estimatedTaxDue"
        ],
        "type": "object"
      },
      "QuarterlySummaryResponse": {
        "properties": {
          "data": {
            "properties": {
              "annualTotal": {
                "properties": {
                  "estimatedTaxDue": {
                    "example": 110000,
                    "format": "decimal",
                    "type": "number"
                  },
                  "purchaseTax": {
                    "example": 330000,
                    "format": "decimal",
                    "type": "number"
                  },
                  "salesTax": {
                    "example": 550000,
                    "format": "decimal",
                    "type": "number"
                  }
                },
                "type": "object"
              },
              "fiscalYear": {
                "example": 2024,
                "type": "integer"
              },
              "quarters": {
                "items": {
                  "$ref": "#/components/schemas/QuarterlySummary"
                },
                "type": "array"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "四半期サマリーを取得しました",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "QuestionOption": {
        "properties": {
          "description": {
            "description": "Optional description",
            "example": "Webアプリケーションやモバイルアプリの開発",
            "type": "string"
          },
          "label": {
            "description": "Display label",
            "example": "ソフトウェア開発",
            "type": "string"
          },
          "value": {
            "description": "Option value",
            "example": "software_development",
            "type": "string"
          }
        },
        "required": [
          "value",
          "label"
        ],
        "type": "object"
      },
      "QueueJob": {
        "properties": {
          "attempts": {
            "description": "Number of processing attempts",
            "example": 1,
            "minimum": 0,
            "type": "number"
          },
          "completedAt": {
            "description": "Processing completion timestamp",
            "example": "2024-01-15T10:30:15.000Z",
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "createdAt": {
            "description": "Job creation timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "data": {
            "additionalProperties": true,
            "description": "Job payload data",
            "example": {
              "fileId": "file123",
              "userId": "user456"
            },
            "type": "object"
          },
          "delay": {
            "default": 0,
            "description": "Delay before processing (milliseconds)",
            "example": 0,
            "type": "number"
          },
          "error": {
            "description": "Error message if job failed",
            "example": "File processing timeout",
            "nullable": true,
            "type": "string"
          },
          "failedAt": {
            "description": "Processing failure timestamp",
            "example": "2024-01-15T10:30:10.000Z",
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "id": {
            "description": "Unique job identifier",
            "example": "job_1640995200000_abc123def",
            "type": "string"
          },
          "maxAttempts": {
            "default": 3,
            "description": "Maximum allowed processing attempts",
            "example": 3,
            "type": "number"
          },
          "metadata": {
            "additionalProperties": true,
            "description": "Additional job metadata",
            "example": {
              "originalName": "document.pdf",
              "userId": "user123"
            },
            "nullable": true,
            "type": "object"
          },
          "priority": {
            "default": 0,
            "description": "Job priority (higher numbers = higher priority)",
            "example": 5,
            "type": "number"
          },
          "scheduledAt": {
            "description": "Scheduled processing time",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "startedAt": {
            "description": "Processing start timestamp",
            "example": "2024-01-15T10:30:05.000Z",
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "status": {
            "description": "Current job status",
            "enum": [
              "pending",
              "processing",
              "completed",
              "failed",
              "retrying",
              "cancelled"
            ],
            "example": "completed",
            "type": "string"
          },
          "type": {
            "description": "Job type identifier",
            "example": "document_processing",
            "type": "string"
          }
        },
        "required": [
          "id",
          "type",
          "data",
          "priority",
          "attempts",
          "maxAttempts",
          "delay",
          "status",
          "createdAt",
          "scheduledAt"
        ],
        "type": "object"
      },
      "QueueStatus": {
        "properties": {
          "completedJobs": {
            "description": "Number of completed jobs",
            "example": 15,
            "type": "integer"
          },
          "failedJobs": {
            "description": "Number of failed jobs",
            "example": 2,
            "type": "integer"
          },
          "pendingJobs": {
            "description": "Number of pending jobs",
            "example": 5,
            "type": "integer"
          },
          "processingJobs": {
            "description": "Number of currently processing jobs",
            "example": 3,
            "type": "integer"
          },
          "totalJobs": {
            "description": "Total number of jobs in queue",
            "example": 25,
            "type": "integer"
          }
        },
        "required": [
          "totalJobs",
          "pendingJobs",
          "processingJobs",
          "completedJobs",
          "failedJobs"
        ],
        "type": "object"
      },
      "QueueStatusResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/QueueStatus"
          },
          "message": {
            "example": "Queue status retrieved successfully",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "QuickHealthResponse": {
        "properties": {
          "pool": {
            "description": "Present ONLY on the keep-warm fan-out (a request carrying a valid x-cron-secret): the connection count before and after re-opening the warm set. Absent for every other caller.",
            "properties": {
              "after": {
                "example": 3,
                "type": "number"
              },
              "before": {
                "example": 1,
                "type": "number"
              }
            },
            "type": "object"
          },
          "requestId": {
            "description": "Request tracing ID",
            "example": "550e8400-e29b-41d4-a716-446655440000",
            "format": "uuid",
            "type": "string"
          },
          "status": {
            "description": "Simple health status",
            "enum": [
              "ok",
              "error"
            ],
            "example": "ok",
            "type": "string"
          },
          "timestamp": {
            "example": "2026-01-15T12:00:00.000Z",
            "format": "date-time",
            "type": "string"
          }
        },
        "type": "object"
      },
      "ReadMethod": {
        "description": "Method used to read or interact with notification",
        "enum": [
          "web",
          "push",
          "email",
          "mobile"
        ],
        "example": "web",
        "type": "string"
      },
      "ReadinessResponse": {
        "properties": {
          "ready": {
            "example": true,
            "type": "boolean"
          },
          "reason": {
            "description": "Reason if not ready or degraded",
            "example": null,
            "nullable": true,
            "type": "string"
          },
          "requestId": {
            "format": "uuid",
            "type": "string"
          },
          "timestamp": {
            "format": "date-time",
            "type": "string"
          }
        },
        "type": "object"
      },
      "RealEstateTransactionResponse": {
        "properties": {
          "data": {
            "properties": {
              "page": {
                "example": 1,
                "type": "integer"
              },
              "total_count": {
                "example": 150,
                "type": "integer"
              },
              "transactions": {
                "items": {
                  "properties": {
                    "area": {
                      "example": 85.5,
                      "type": "number"
                    },
                    "building_year": {
                      "example": 2020,
                      "type": "integer"
                    },
                    "frontage": {
                      "example": 8.5,
                      "type": "number"
                    },
                    "land_shape": {
                      "example": "長方形",
                      "type": "string"
                    },
                    "price": {
                      "example": 50000000,
                      "type": "number"
                    },
                    "structure": {
                      "example": "RC",
                      "type": "string"
                    },
                    "transaction_date": {
                      "example": "2024-01-15",
                      "format": "date",
                      "type": "string"
                    },
                    "transaction_id": {
                      "example": "txn_123456",
                      "type": "string"
                    },
                    "use": {
                      "example": "住宅",
                      "type": "string"
                    }
                  },
                  "type": "object"
                },
                "type": "array"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Real estate transactions retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "type": "object"
      },
      "RecentAchievement": {
        "properties": {
          "achievement_id": {
            "example": "first_login",
            "type": "string"
          },
          "earned_at": {
            "format": "date-time",
            "type": "string"
          },
          "tier": {
            "enum": [
              "bronze",
              "silver",
              "gold",
              "platinum"
            ],
            "nullable": true,
            "type": "string"
          }
        },
        "type": "object"
      },
      "RecentChanges": {
        "properties": {
          "docs": {
            "description": "Recent documentation commits",
            "items": {
              "$ref": "#/components/schemas/GitCommit"
            },
            "type": "array"
          },
          "features": {
            "description": "Recent feature commits",
            "items": {
              "$ref": "#/components/schemas/GitCommit"
            },
            "type": "array"
          },
          "fixes": {
            "description": "Recent bug fix commits",
            "items": {
              "$ref": "#/components/schemas/GitCommit"
            },
            "type": "array"
          },
          "other": {
            "description": "Other recent commits",
            "items": {
              "$ref": "#/components/schemas/GitCommit"
            },
            "type": "array"
          }
        },
        "required": [
          "features",
          "fixes",
          "docs",
          "other"
        ],
        "type": "object"
      },
      "RecentChangesResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/RecentChanges"
          },
          "message": {
            "example": "Recent changes retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "RecommendedModelsResponse": {
        "properties": {
          "data": {
            "properties": {
              "count": {
                "description": "Number of recommended models",
                "example": 12,
                "type": "integer"
              },
              "models": {
                "description": "Recommended models across all providers",
                "items": {
                  "$ref": "#/components/schemas/AIModel"
                },
                "type": "array"
              }
            },
            "required": [
              "models",
              "count"
            ],
            "type": "object"
          },
          "message": {
            "example": "Recommended models retrieved successfully",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ReconciliationActionResponse": {
        "properties": {
          "data": {
            "properties": {
              "details": {
                "description": "Action-specific details and results",
                "type": "object"
              },
              "processed_count": {
                "example": 1,
                "type": "integer"
              },
              "success": {
                "example": true,
                "type": "boolean"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Reconciliation action completed successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ReconciliationMethod": {
        "description": "Method used for reconciliation matching",
        "enum": [
          "auto_exact",
          "auto_fuzzy",
          "manual",
          "rule_based",
          "bulk_reimbursement"
        ],
        "example": "auto_exact",
        "type": "string"
      },
      "ReconciliationPattern": {
        "properties": {
          "amount_pattern": {
            "description": "Amount pattern statistics",
            "properties": {
              "average": {
                "format": "decimal",
                "type": "number"
              },
              "max": {
                "format": "decimal",
                "type": "number"
              },
              "min": {
                "format": "decimal",
                "type": "number"
              },
              "variance": {
                "format": "decimal",
                "type": "number"
              }
            },
            "type": "object"
          },
          "confidence_score": {
            "description": "Pattern confidence score",
            "example": 0.92,
            "format": "decimal",
            "maximum": 1,
            "minimum": 0,
            "type": "number"
          },
          "description_pattern": {
            "description": "Transaction description pattern",
            "example": "家賃.*オフィス",
            "type": "string"
          },
          "frequency_pattern": {
            "description": "Detected frequency pattern",
            "enum": [
              "daily",
              "weekly",
              "monthly",
              "quarterly",
              "yearly",
              "irregular"
            ],
            "example": "monthly",
            "type": "string"
          },
          "id": {
            "description": "Pattern unique identifier",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "last_occurrence": {
            "description": "Last occurrence of this pattern",
            "example": "2024-01-15T00:00:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "occurrences": {
            "description": "Number of pattern occurrences detected",
            "example": 12,
            "minimum": 1,
            "type": "integer"
          },
          "pattern_name": {
            "description": "Detected pattern name",
            "example": "Monthly Office Rent",
            "type": "string"
          }
        },
        "required": [
          "id",
          "pattern_name",
          "description_pattern",
          "amount_pattern",
          "frequency_pattern",
          "confidence_score",
          "occurrences",
          "last_occurrence"
        ],
        "type": "object"
      },
      "ReconciliationPatternsResponse": {
        "properties": {
          "data": {
            "items": {
              "$ref": "#/components/schemas/ReconciliationPattern"
            },
            "type": "array"
          },
          "message": {
            "example": "Reconciliation patterns retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ReconciliationRule": {
        "properties": {
          "action_config": {
            "description": "Configuration for the rule action",
            "example": {
              "confidence_threshold": 0.8,
              "require_manual_review": false,
              "target_account": "6100"
            },
            "nullable": true,
            "type": "object"
          },
          "action_type": {
            "description": "Type of action to perform when rule matches",
            "example": "auto_match",
            "maxLength": 20,
            "type": "string"
          },
          "created_at": {
            "description": "Rule creation timestamp",
            "example": "2024-01-01T00:00:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "description": {
            "description": "Rule description and purpose",
            "example": "Automatically match office supply purchases from specific vendors",
            "nullable": true,
            "type": "string"
          },
          "id": {
            "description": "Rule unique identifier",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "is_active": {
            "description": "Whether the rule is currently active",
            "example": true,
            "type": "boolean"
          },
          "last_applied_at": {
            "description": "Last time rule was applied",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "match_criteria": {
            "description": "JSON criteria for matching conditions",
            "example": {
              "amount_range": {
                "max": 50000,
                "min": 1000
              },
              "counterparty_patterns": [
                ".*用品.*",
                ".*SUPPLY.*"
              ],
              "description_contains": [
                "オフィス用品",
                "OFFICE"
              ]
            },
            "type": "object"
          },
          "name": {
            "description": "Rule name for identification",
            "example": "Office Supplies Auto-Match",
            "maxLength": 100,
            "type": "string"
          },
          "priority": {
            "description": "Rule execution priority (lower = higher priority)",
            "example": 100,
            "maximum": 999,
            "minimum": 1,
            "type": "integer"
          },
          "times_applied": {
            "description": "Number of times rule has been applied",
            "example": 25,
            "minimum": 0,
            "type": "integer"
          },
          "updated_at": {
            "description": "Rule last update timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          }
        },
        "required": [
          "id",
          "name",
          "priority",
          "is_active",
          "match_criteria",
          "action_type",
          "times_applied",
          "created_at",
          "updated_at"
        ],
        "type": "object"
      },
      "ReconciliationRulesResponse": {
        "properties": {
          "data": {
            "items": {
              "$ref": "#/components/schemas/ReconciliationRule"
            },
            "type": "array"
          },
          "message": {
            "example": "Reconciliation rules retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ReconciliationStatus": {
        "description": "Status of bank transaction reconciliation",
        "enum": [
          "pending",
          "matched",
          "partially_matched",
          "excluded",
          "suspense"
        ],
        "example": "pending",
        "type": "string"
      },
      "RecordActivityRequest": {
        "description": "Request body for recording a single activity. Use camelCase for all fields.",
        "properties": {
          "actionLabel": {
            "description": "Japanese display label (e.g., 書類を削除)",
            "maxLength": 255,
            "type": "string"
          },
          "actionType": {
            "description": "Type of activity (e.g., document_delete, page_visit)",
            "enum": [
              "document_view",
              "document_edit",
              "document_create",
              "document_delete",
              "document_generate",
              "document_download",
              "document_print",
              "document_send",
              "document_share",
              "document_sign",
              "document_stamp",
              "document_archive",
              "document_restore",
              "document_duplicate",
              "document_update",
              "document_lock",
              "document_unlock",
              "document_void",
              "settings_company",
              "settings_accounting",
              "settings_auth",
              "settings_inkan",
              "settings_signature",
              "settings_profile",
              "settings_notification",
              "settings_payment",
              "settings_integration",
              "settings_export",
              "settings_import",
              "journal_entry",
              "journal_view",
              "journal_delete",
              "journal_approve",
              "journal_reject",
              "bank_reconcile",
              "fiscal_period",
              "account_create",
              "account_edit",
              "account_delete",
              "account_view",
              "trial_balance_view",
              "trial_balance_export",
              "report_view",
              "report_generate",
              "report_export",
              "report_print",
              "report_schedule",
              "client_create",
              "client_edit",
              "client_delete",
              "client_view",
              "ai_chat",
              "ai_suggestion_accept",
              "ai_suggestion_reject",
              "ai_reconcile",
              "ai_analyze",
              "page_visit",
              "session_start",
              "session_end",
              "session_resume",
              "tab_switch",
              "modal_open",
              "modal_close",
              "search_execute",
              "filter_apply",
              "sort_change",
              "form_submit",
              "form_save_draft",
              "form_validation_error",
              "error_occurred",
              "api_error",
              "network_error",
              "login",
              "logout",
              "password_change",
              "mfa_enable",
              "mfa_disable",
              "bulk_upload",
              "bulk_delete",
              "csv_import",
              "csv_export",
              "other"
            ],
            "type": "string"
          },
          "browser": {
            "maxLength": 50,
            "type": "string"
          },
          "companyId": {
            "format": "uuid",
            "type": "string"
          },
          "deviceType": {
            "enum": [
              "desktop",
              "tablet",
              "mobile"
            ],
            "type": "string"
          },
          "durationMs": {
            "description": "Time spent in milliseconds",
            "minimum": 0,
            "type": "integer"
          },
          "entityId": {
            "description": "Valid UUID v4 only. Omit for page views without DB entity.",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "entityName": {
            "maxLength": 255,
            "type": "string"
          },
          "entityType": {
            "description": "Entity type: document, journal, page, etc.",
            "maxLength": 50,
            "type": "string"
          },
          "errorMessage": {
            "maxLength": 1000,
            "type": "string"
          },
          "isError": {
            "description": "Whether this activity represents an error",
            "type": "boolean"
          },
          "metadata": {
            "type": "object"
          },
          "os": {
            "maxLength": 50,
            "type": "string"
          },
          "referrer": {
            "maxLength": 500,
            "type": "string"
          },
          "route": {
            "description": "Frontend route path",
            "maxLength": 255,
            "type": "string"
          },
          "routeParams": {
            "description": "Route parameters",
            "type": "object"
          },
          "sessionId": {
            "description": "Frontend session ID",
            "maxLength": 64,
            "type": "string"
          },
          "timestamp": {
            "description": "Override timestamp for offline sync",
            "format": "date-time",
            "type": "string"
          },
          "userAgent": {
            "maxLength": 500,
            "type": "string"
          }
        },
        "required": [
          "actionType",
          "actionLabel",
          "route"
        ],
        "type": "object"
      },
      "RecordClientUsageRequest": {
        "properties": {
          "api_key_source": {
            "$ref": "#/components/schemas/ClientUsageApiKeySource",
            "description": "Source of the API key used (required)"
          },
          "completion_tokens": {
            "description": "Number of tokens in the completion/output (required)",
            "example": 75,
            "maximum": 1000000,
            "minimum": 0,
            "type": "integer"
          },
          "cost_estimate": {
            "description": "Estimated cost in USD as decimal string (max 6 decimal places, e.g., \"0.001234\"). Maximum $100 per request.",
            "example": "0.0045",
            "pattern": "^\\d+(\\.\\d{1,6})?$",
            "type": "string"
          },
          "model_used": {
            "description": "AI model identifier. Should match a model_name in ai_configs for accurate pricing. If no exact match, service will attempt normalization. Check /api/ai-models for valid names.",
            "example": "gpt-4o",
            "maxLength": 100,
            "type": "string"
          },
          "operation_type": {
            "$ref": "#/components/schemas/ClientUsageOperationType",
            "description": "Type of AI operation performed (required)"
          },
          "processing_time_ms": {
            "description": "Processing time in milliseconds (optional)",
            "example": 1250,
            "maximum": 600000,
            "minimum": 0,
            "type": "integer"
          },
          "prompt_tokens": {
            "description": "Number of tokens in the prompt/input (required)",
            "example": 150,
            "maximum": 1000000,
            "minimum": 0,
            "type": "integer"
          },
          "request_id": {
            "description": "Idempotency key (UUID v4). If provided, duplicate requests within 5 minutes will return the existing record instead of creating a new one. Recommended for production to safely handle network retries.",
            "example": "550e8400-e29b-41d4-a716-446655440000",
            "format": "uuid",
            "type": "string"
          },
          "request_metadata": {
            "description": "Additional metadata about the request (optional). Avoid storing PII.",
            "example": {
              "document_type": "pdf",
              "file_size_mb": 2.3,
              "page_count": 5
            },
            "type": "object"
          },
          "total_tokens": {
            "description": "Total tokens used. Must equal prompt_tokens + completion_tokens (1% tolerance allowed for different tokenizer implementations).",
            "example": 225,
            "maximum": 2000000,
            "minimum": 0,
            "type": "integer"
          }
        },
        "required": [
          "operation_type",
          "model_used",
          "prompt_tokens",
          "completion_tokens",
          "total_tokens",
          "api_key_source"
        ],
        "type": "object"
      },
      "RecordCorrectionRequest": {
        "example": {
          "corrected_category": 20,
          "correction_reason": "来客用の購入なので福利厚生費",
          "original_amount": 500,
          "original_description": "コーヒー",
          "original_vendor": "スターバックス",
          "suggested_category": 1,
          "suggestion_source": "vendor_rule"
        },
        "properties": {
          "corrected_category": {
            "maximum": 26,
            "minimum": 0,
            "type": "integer"
          },
          "correction_reason": {
            "maxLength": 500,
            "type": "string"
          },
          "item_id": {
            "format": "uuid",
            "type": "string"
          },
          "matched_rule_id": {
            "format": "uuid",
            "type": "string"
          },
          "original_amount": {
            "minimum": 0,
            "type": "number"
          },
          "original_description": {
            "maxLength": 2000,
            "type": "string"
          },
          "original_vendor": {
            "maxLength": 500,
            "type": "string"
          },
          "session_id": {
            "format": "uuid",
            "type": "string"
          },
          "suggested_category": {
            "maximum": 26,
            "minimum": 0,
            "type": "integer"
          },
          "suggestion_confidence": {
            "maximum": 1,
            "minimum": 0,
            "type": "number"
          },
          "suggestion_source": {
            "$ref": "#/components/schemas/SuggestionSource"
          }
        },
        "required": [
          "suggested_category",
          "suggestion_source",
          "corrected_category"
        ],
        "type": "object"
      },
      "RecordTimeSavedRequest": {
        "properties": {
          "metadata": {
            "type": "object"
          },
          "minutes": {
            "example": 15,
            "maximum": 480,
            "minimum": 1,
            "type": "integer"
          },
          "source": {
            "example": "ai_reconciliation",
            "maxLength": 50,
            "type": "string"
          },
          "source_entity_id": {
            "format": "uuid",
            "type": "string"
          }
        },
        "required": [
          "minutes",
          "source"
        ],
        "type": "object"
      },
      "RecordUsageResponse": {
        "properties": {
          "data": {
            "properties": {
              "cost_estimate": {
                "description": "Calculated cost estimate in USD",
                "example": 0.0045,
                "format": "decimal",
                "type": "number"
              },
              "id": {
                "description": "Usage record unique identifier",
                "example": "123e4567-e89b-12d3-a456-426614174000",
                "format": "uuid",
                "type": "string"
              },
              "is_duplicate": {
                "description": "True if this is a duplicate request (request_id matched existing record)",
                "example": false,
                "type": "boolean"
              },
              "model_used": {
                "description": "Normalized model name used for pricing. May differ from input if normalization occurred.",
                "example": "gpt-4o",
                "type": "string"
              },
              "warnings": {
                "description": "Array of warnings about the request (e.g., model normalization, fallback pricing, zero tokens)",
                "example": [
                  "Model \"gpt4o\" normalized to \"gpt-4o\". Use \"gpt-4o\" for accurate pricing.",
                  "Model \"custom-model\" not found in ai_configs. Using fallback pricing ($3/$12 per million tokens)."
                ],
                "items": {
                  "type": "string"
                },
                "type": "array"
              }
            },
            "required": [
              "id",
              "cost_estimate",
              "model_used"
            ],
            "type": "object"
          },
          "message": {
            "description": "Status message indicating success or duplicate detection",
            "example": "Usage recorded successfully",
            "type": "string"
          },
          "statusCode": {
            "description": "201 for new records, 200 for duplicate requests (when request_id matches existing)",
            "example": 201,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "RecoveryCodesStatusResponse": {
        "properties": {
          "data": {
            "properties": {
              "generatedAt": {
                "format": "date-time",
                "nullable": true,
                "type": "string"
              },
              "hasRecoveryCodes": {
                "type": "boolean"
              },
              "lastUsedAt": {
                "format": "date-time",
                "nullable": true,
                "type": "string"
              },
              "remainingCodes": {
                "example": 6,
                "type": "integer"
              },
              "totalCodes": {
                "example": 8,
                "type": "integer"
              },
              "usedCodes": {
                "example": 2,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "type": "object"
      },
      "RecoveryMethodsResponse": {
        "properties": {
          "data": {
            "properties": {
              "backupEmailMasked": {
                "example": "ba***@example.com",
                "nullable": true,
                "type": "string"
              },
              "primaryEmailMasked": {
                "example": "ke***@gmail.com",
                "type": "string"
              },
              "recoveryMethods": {
                "properties": {
                  "backupEmail": {
                    "type": "boolean"
                  },
                  "googleRelink": {
                    "type": "boolean"
                  },
                  "recoveryCodes": {
                    "type": "boolean"
                  }
                },
                "type": "object"
              }
            },
            "type": "object"
          },
          "message": {
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "type": "object"
      },
      "RedeemReferralRequest": {
        "properties": {
          "code": {
            "example": "A2K9PQRS",
            "pattern": "^[A-HJ-KM-NP-Z2-9]{8}$",
            "type": "string"
          }
        },
        "required": [
          "code"
        ],
        "type": "object"
      },
      "ReferenceDataMeta": {
        "properties": {
          "generatedAt": {
            "description": "Data generation timestamp",
            "example": "2024-03-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "locale": {
            "description": "Default locale",
            "example": "ja-JP",
            "type": "string"
          },
          "version": {
            "description": "Reference data version",
            "example": "1.0.0",
            "type": "string"
          }
        },
        "required": [
          "version",
          "generatedAt",
          "locale"
        ],
        "type": "object"
      },
      "ReferralCodeResponse": {
        "properties": {
          "code": {
            "example": "A2K9PQRS",
            "maxLength": 8,
            "minLength": 8,
            "type": "string"
          },
          "shareUrl": {
            "example": "https://6-6-ai.vercel.app/login?ref=A2K9PQRS",
            "type": "string"
          },
          "stats": {
            "$ref": "#/components/schemas/ReferralStats"
          }
        },
        "required": [
          "code",
          "shareUrl",
          "stats"
        ],
        "type": "object"
      },
      "ReferralHistoryRow": {
        "properties": {
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "onboardedAt": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "refereeMaskedName": {
            "example": "田〇〇",
            "type": "string"
          },
          "rewardedAt": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "signupAt": {
            "format": "date-time",
            "type": "string"
          },
          "status": {
            "enum": [
              "pending_onboarding",
              "rewarded",
              "capped",
              "fraud_flagged",
              "expired"
            ],
            "type": "string"
          }
        },
        "type": "object"
      },
      "ReferralStats": {
        "properties": {
          "monthThisMonth": {
            "example": 1,
            "type": "integer"
          },
          "monthlyCapRemaining": {
            "example": 9,
            "type": "integer"
          },
          "pending": {
            "example": 2,
            "type": "integer"
          },
          "recentReferrals": {
            "items": {
              "$ref": "#/components/schemas/ReferralHistoryRow"
            },
            "type": "array"
          },
          "totalRewarded": {
            "example": 3,
            "type": "integer"
          }
        },
        "type": "object"
      },
      "RegisterDocumentRequest": {
        "properties": {
          "amount": {
            "description": "Transaction amount in JPY",
            "example": 125000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "currency_code": {
            "default": "JPY",
            "description": "Currency code (ISO 4217)",
            "example": "JPY",
            "type": "string"
          },
          "description": {
            "description": "Transaction description",
            "example": "Office supplies purchase",
            "type": "string"
          },
          "document_id": {
            "description": "Document unique identifier",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "document_type": {
            "$ref": "#/components/schemas/EBookDocumentType"
          },
          "file_hash": {
            "description": "SHA-256 hash for file integrity",
            "example": "a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3",
            "type": "string"
          },
          "original_file_name": {
            "description": "Original file name",
            "example": "receipt_20240315.pdf",
            "type": "string"
          },
          "storage_url": {
            "description": "File storage URL",
            "example": "https://storage.example.com/documents/receipt_20240315.pdf",
            "format": "uri",
            "type": "string"
          },
          "transaction_date": {
            "description": "Transaction date in YYYYMMDD format",
            "example": 20240315,
            "type": "integer"
          },
          "vendor_name": {
            "description": "Vendor/payee name (required for legal search)",
            "example": "株式会社サンプル",
            "minLength": 1,
            "type": "string"
          }
        },
        "required": [
          "document_id",
          "transaction_date",
          "amount",
          "vendor_name"
        ],
        "type": "object"
      },
      "RegisteredCreditCard": {
        "properties": {
          "bankAccountSettings": {
            "description": "Linked bank account details",
            "nullable": true,
            "properties": {
              "accountNumber": {
                "type": "string"
              },
              "accountType": {
                "type": "string"
              },
              "bankName": {
                "type": "string"
              },
              "id": {
                "format": "uuid",
                "type": "string"
              }
            },
            "type": "object"
          },
          "brand": {
            "description": "Card brand",
            "enum": [
              "VISA",
              "Mastercard",
              "JCB",
              "AMEX",
              "Diners"
            ],
            "nullable": true,
            "type": "string"
          },
          "cardName": {
            "description": "Display name for the card",
            "example": "楽天カード（メイン）",
            "type": "string"
          },
          "closingDay": {
            "description": "Statement closing day (締め日)",
            "example": 15,
            "maximum": 31,
            "minimum": 1,
            "nullable": true,
            "type": "integer"
          },
          "color": {
            "description": "Hex color for UI display",
            "example": "#6366f1",
            "pattern": "^#[0-9A-Fa-f]{6}$",
            "type": "string"
          },
          "companyId": {
            "description": "Associated company ID",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "createdAt": {
            "description": "Creation timestamp",
            "format": "date-time",
            "type": "string"
          },
          "icon": {
            "description": "Icon identifier for UI",
            "nullable": true,
            "type": "string"
          },
          "id": {
            "description": "Unique identifier",
            "format": "uuid",
            "type": "string"
          },
          "isActive": {
            "description": "Whether the card is active (false = soft deleted)",
            "type": "boolean"
          },
          "issuer": {
            "description": "Card issuer name",
            "example": "楽天カード株式会社",
            "nullable": true,
            "type": "string"
          },
          "lastFourDigits": {
            "description": "Last 4 digits of card number",
            "example": "1234",
            "pattern": "^\\d{4}$",
            "type": "string"
          },
          "linkedBankAccountId": {
            "description": "Linked bank account for automatic payment",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "notes": {
            "description": "User notes about the card",
            "nullable": true,
            "type": "string"
          },
          "paymentDay": {
            "description": "Payment due day (引落日)",
            "example": 10,
            "maximum": 31,
            "minimum": 1,
            "nullable": true,
            "type": "integer"
          },
          "updatedAt": {
            "description": "Last update timestamp",
            "format": "date-time",
            "type": "string"
          },
          "userId": {
            "description": "Owner user ID",
            "format": "uuid",
            "type": "string"
          }
        },
        "type": "object"
      },
      "RegistryHealthCheck": {
        "properties": {
          "deadline_due_date": {
            "format": "date",
            "nullable": true,
            "type": "string"
          },
          "detail_ja": {
            "type": "string"
          },
          "key": {
            "type": "string"
          },
          "label_ja": {
            "type": "string"
          },
          "status": {
            "enum": [
              "ok",
              "warn",
              "critical"
            ],
            "type": "string"
          }
        },
        "type": "object"
      },
      "ReimbursementWorkflowSummary": {
        "properties": {
          "claimsDocuments": {
            "description": "Claims documents in the workflow",
            "items": {
              "$ref": "#/components/schemas/ClaimsDocumentSummary"
            },
            "type": "array"
          },
          "paymentDocuments": {
            "description": "Payment documents in the workflow",
            "items": {
              "$ref": "#/components/schemas/PaymentDocumentSummary"
            },
            "type": "array"
          },
          "progress": {
            "description": "Workflow completion percentage",
            "example": 65,
            "maximum": 100,
            "minimum": 0,
            "type": "number"
          },
          "salarySlipDocuments": {
            "description": "Salary slips reached by the chain walk, including multi-hop ones (Wave 9.5). Absent on the error path.",
            "items": {
              "$ref": "#/components/schemas/SalarySlipDocumentSummary"
            },
            "type": "array"
          },
          "totalReimbursementAmount": {
            "description": "Total amount across all documents in workflow",
            "example": 45000,
            "type": "number"
          },
          "travelReport": {
            "$ref": "#/components/schemas/TravelReportSummary",
            "description": "Travel report document (if exists in workflow)"
          },
          "workflowStage": {
            "description": "Current workflow stage in Japanese",
            "enum": [
              "出張",
              "経費",
              "支払",
              "アーカイブ"
            ],
            "example": "経費",
            "type": "string"
          }
        },
        "required": [
          "claimsDocuments",
          "paymentDocuments",
          "workflowStage",
          "progress",
          "totalReimbursementAmount"
        ],
        "type": "object"
      },
      "ReimbursementWorkflowSummaryResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/ReimbursementWorkflowSummary"
          },
          "message": {
            "example": "Reimbursement workflow summary retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ReimbursementWorkflowType": {
        "description": "Reimbursement workflow linking types",
        "enum": [
          "travel_to_claims",
          "claims_to_payment"
        ],
        "example": "travel_to_claims",
        "type": "string"
      },
      "RemarkCreateResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/RemarkDictionary"
          },
          "message": {
            "example": "Remark created successfully",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "RemarkDeleteResponse": {
        "properties": {
          "data": {
            "properties": {
              "deleted": {
                "example": true,
                "type": "boolean"
              },
              "id": {
                "example": "123e4567-e89b-12d3-a456-426614174000",
                "format": "uuid",
                "type": "string"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Remark deleted successfully",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "RemarkDictionary": {
        "properties": {
          "accounts": {
            "allOf": [
              {
                "$ref": "#/components/schemas/AccountInfo"
              },
              {
                "nullable": true
              }
            ],
            "description": "Linked account information"
          },
          "created_at": {
            "description": "Creation timestamp",
            "example": "2024-03-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "id": {
            "description": "Remark ID",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "is_active": {
            "description": "Whether remark is active",
            "example": true,
            "type": "boolean"
          },
          "last_used_at": {
            "description": "Last usage timestamp",
            "example": "2024-03-15T10:30:00.000Z",
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "linked_account_id": {
            "description": "Linked account ID for categorization",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "linked_category": {
            "description": "Linked expense category",
            "example": 3,
            "nullable": true,
            "type": "integer"
          },
          "reading": {
            "description": "Reading (フリガナ) for Japanese text",
            "example": "でんしゃだい",
            "nullable": true,
            "type": "string"
          },
          "remark_text": {
            "description": "Remark text for journal entries",
            "example": "電車代（東京駅→大阪駅）",
            "type": "string"
          },
          "updated_at": {
            "description": "Last update timestamp",
            "example": "2024-03-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "usage_count": {
            "description": "Number of times remark has been used",
            "example": 25,
            "type": "integer"
          },
          "user_id": {
            "description": "Owner user ID",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          }
        },
        "required": [
          "id",
          "user_id",
          "remark_text",
          "usage_count",
          "is_active",
          "created_at",
          "updated_at"
        ],
        "type": "object"
      },
      "RemarkListResponse": {
        "properties": {
          "data": {
            "items": {
              "$ref": "#/components/schemas/RemarkDictionary"
            },
            "type": "array"
          },
          "message": {
            "example": "Remark dictionary retrieved successfully",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "RemarkResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/RemarkDictionary"
          },
          "message": {
            "example": "Remark retrieved successfully",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "RemarkSuggestion": {
        "properties": {
          "accounts": {
            "allOf": [
              {
                "$ref": "#/components/schemas/AccountInfo"
              },
              {
                "nullable": true
              }
            ],
            "description": "Linked account information"
          },
          "id": {
            "description": "Remark ID",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "reading": {
            "description": "Reading (フリガナ)",
            "example": "でんしゃだい",
            "nullable": true,
            "type": "string"
          },
          "remark_text": {
            "description": "Remark text",
            "example": "電車代（東京駅→大阪駅）",
            "type": "string"
          },
          "usage_count": {
            "description": "Usage count for popularity ranking",
            "example": 25,
            "type": "integer"
          }
        },
        "required": [
          "id",
          "remark_text",
          "usage_count"
        ],
        "type": "object"
      },
      "RemarkSuggestionsResponse": {
        "properties": {
          "data": {
            "items": {
              "$ref": "#/components/schemas/RemarkSuggestion"
            },
            "type": "array"
          },
          "message": {
            "example": "Suggestions retrieved successfully",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "RemarkUpdateResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/RemarkDictionary"
          },
          "message": {
            "example": "Remark updated successfully",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "Reminder": {
        "properties": {
          "created_at": {
            "description": "Reminder creation timestamp",
            "example": "2024-01-01T00:00:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "day": {
            "description": "Day of month/week for reminder",
            "example": 17,
            "maximum": 31,
            "minimum": 1,
            "nullable": true,
            "type": "integer"
          },
          "days_until_due": {
            "description": "Number of days until reminder is due",
            "example": 5,
            "minimum": 0,
            "type": "integer"
          },
          "deleted_at": {
            "description": "Reminder deletion timestamp",
            "example": null,
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "id": {
            "description": "Reminder unique identifier",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "is_deleted": {
            "description": "Whether the reminder has been deleted",
            "example": false,
            "type": "boolean"
          },
          "is_done": {
            "description": "Whether the reminder has been completed",
            "example": false,
            "type": "boolean"
          },
          "month": {
            "description": "Month for yearly reminders",
            "example": 4,
            "maximum": 12,
            "minimum": 1,
            "nullable": true,
            "type": "integer"
          },
          "next_due_date": {
            "description": "Next due date for this reminder",
            "example": "2024-04-17",
            "format": "date",
            "type": "string"
          },
          "reminder_cycle": {
            "$ref": "#/components/schemas/ReminderCycle"
          },
          "reminder_type": {
            "$ref": "#/components/schemas/ReminderType"
          },
          "title": {
            "description": "Reminder title or description",
            "example": "法人税申告書提出期限",
            "maxLength": 255,
            "type": "string"
          },
          "updated_at": {
            "description": "Reminder last update timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "urgency_level": {
            "description": "Urgency level based on days until due",
            "enum": [
              "low",
              "medium",
              "high",
              "critical"
            ],
            "example": "high",
            "type": "string"
          },
          "user_id": {
            "description": "User who owns this reminder",
            "example": "abc12345-def6-7890-ghij-klmnopqrstuv",
            "format": "uuid",
            "type": "string"
          },
          "week_day": {
            "description": "Day of week for weekly reminders (0=Sunday, 6=Saturday)",
            "example": 1,
            "maximum": 6,
            "minimum": 0,
            "nullable": true,
            "type": "integer"
          },
          "year": {
            "description": "Specific year for one-time reminders",
            "example": 2024,
            "maximum": 2099,
            "minimum": 2020,
            "nullable": true,
            "type": "integer"
          }
        },
        "required": [
          "id",
          "user_id",
          "title",
          "reminder_type",
          "reminder_cycle",
          "is_done",
          "is_deleted",
          "created_at",
          "updated_at"
        ],
        "type": "object"
      },
      "ReminderActionResponse": {
        "properties": {
          "data": {
            "properties": {
              "reminder_id": {
                "format": "uuid",
                "type": "string"
              },
              "success": {
                "example": true,
                "type": "boolean"
              },
              "updated_at": {
                "format": "date-time",
                "type": "string"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Reminder marked as done successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ReminderConfig": {
        "properties": {
          "consumption_tax_active": {
            "description": "Whether consumption tax reminders are active",
            "example": true,
            "type": "boolean"
          },
          "consumption_tax_day": {
            "description": "Day for consumption tax reminders (消費税)",
            "example": 17,
            "maximum": 31,
            "minimum": 1,
            "nullable": true,
            "type": "integer"
          },
          "consumption_tax_month": {
            "description": "Month for consumption tax reminders",
            "example": 4,
            "maximum": 12,
            "minimum": 1,
            "nullable": true,
            "type": "integer"
          },
          "corporate_tax_active": {
            "description": "Whether corporate tax reminders are active",
            "example": true,
            "type": "boolean"
          },
          "corporate_tax_day": {
            "description": "Day of month for corporate tax reminders",
            "example": 17,
            "maximum": 31,
            "minimum": 1,
            "nullable": true,
            "type": "integer"
          },
          "corporate_tax_month": {
            "description": "Month for corporate tax reminders (Japanese fiscal year)",
            "example": 4,
            "maximum": 12,
            "minimum": 1,
            "nullable": true,
            "type": "integer"
          },
          "created_at": {
            "description": "Configuration creation timestamp",
            "example": "2024-01-01T00:00:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "depreciable_assets_active": {
            "description": "Whether 償却資産申告 reminders are active (default: true)",
            "example": true,
            "type": "boolean"
          },
          "depreciable_assets_day": {
            "description": "Day for 償却資産申告 submission (fixed: 31)",
            "example": 31,
            "maximum": 31,
            "minimum": 1,
            "nullable": true,
            "type": "integer"
          },
          "depreciable_assets_month": {
            "description": "Month for 償却資産申告 submission (fixed: January)",
            "example": 1,
            "maximum": 12,
            "minimum": 1,
            "nullable": true,
            "type": "integer"
          },
          "expense_payment_active": {
            "description": "Whether expense payment reminders are active",
            "example": true,
            "type": "boolean"
          },
          "expense_payment_day": {
            "description": "Day of month for expense payment reminders",
            "example": 30,
            "maximum": 31,
            "minimum": 1,
            "nullable": true,
            "type": "integer"
          },
          "final_tax_return_active": {
            "description": "Whether 確定申告 reminders are active (auto-enabled for 乙欄 users)",
            "example": false,
            "type": "boolean"
          },
          "final_tax_return_day": {
            "description": "Day for 確定申告 submission (default: 15)",
            "example": 15,
            "maximum": 31,
            "minimum": 1,
            "nullable": true,
            "type": "integer"
          },
          "final_tax_return_month": {
            "description": "Month for 確定申告 submission (default: March)",
            "example": 3,
            "maximum": 12,
            "minimum": 1,
            "nullable": true,
            "type": "integer"
          },
          "id": {
            "description": "Reminder configuration unique identifier",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "invoice_active": {
            "description": "Whether invoice reminders are active",
            "example": true,
            "type": "boolean"
          },
          "invoice_day": {
            "description": "Day of month for invoice reminders",
            "example": 25,
            "maximum": 31,
            "minimum": 1,
            "nullable": true,
            "type": "integer"
          },
          "labor_insurance_active": {
            "description": "Whether labor insurance reminders are active",
            "example": true,
            "type": "boolean"
          },
          "labor_insurance_day": {
            "description": "Day for labor insurance reminders (労働保険)",
            "example": 10,
            "maximum": 31,
            "minimum": 1,
            "nullable": true,
            "type": "integer"
          },
          "labor_insurance_month": {
            "description": "Month for labor insurance reminders",
            "example": 7,
            "maximum": 12,
            "minimum": 1,
            "nullable": true,
            "type": "integer"
          },
          "legal_records_summary_active": {
            "description": "Whether 法定調書合計表 reminders are active (default: true)",
            "example": true,
            "type": "boolean"
          },
          "legal_records_summary_day": {
            "description": "Day for 法定調書合計表 submission (fixed: 31)",
            "example": 31,
            "maximum": 31,
            "minimum": 1,
            "nullable": true,
            "type": "integer"
          },
          "legal_records_summary_month": {
            "description": "Month for 法定調書合計表 submission (fixed: January)",
            "example": 1,
            "maximum": 12,
            "minimum": 1,
            "nullable": true,
            "type": "integer"
          },
          "reimbursement_active": {
            "description": "Whether reimbursement reminders are active",
            "example": true,
            "type": "boolean"
          },
          "reimbursement_day": {
            "description": "Day of month for reimbursement reminders",
            "example": 25,
            "maximum": 31,
            "minimum": 1,
            "nullable": true,
            "type": "integer"
          },
          "salary_payment_report_active": {
            "description": "Whether 給与支払報告書 reminders are active (default: true)",
            "example": true,
            "type": "boolean"
          },
          "salary_payment_report_day": {
            "description": "Day for 給与支払報告書 submission (fixed: 31)",
            "example": 31,
            "maximum": 31,
            "minimum": 1,
            "nullable": true,
            "type": "integer"
          },
          "salary_payment_report_month": {
            "description": "Month for 給与支払報告書 submission (fixed: January)",
            "example": 1,
            "maximum": 12,
            "minimum": 1,
            "nullable": true,
            "type": "integer"
          },
          "social_insurance_active": {
            "description": "Whether social insurance reminders are active",
            "example": true,
            "type": "boolean"
          },
          "social_insurance_day": {
            "description": "Day for social insurance reminders (社会保険)",
            "example": 10,
            "maximum": 31,
            "minimum": 1,
            "nullable": true,
            "type": "integer"
          },
          "social_insurance_month": {
            "description": "Month for social insurance reminders",
            "example": 7,
            "maximum": 12,
            "minimum": 1,
            "nullable": true,
            "type": "integer"
          },
          "updated_at": {
            "description": "Configuration last update timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "user_id": {
            "description": "User who owns this configuration",
            "example": "abc12345-def6-7890-ghij-klmnopqrstuv",
            "format": "uuid",
            "type": "string"
          },
          "withholding_tax_slip_active": {
            "description": "Whether 源泉徴収票 reminders are active (default: true)",
            "example": true,
            "type": "boolean"
          },
          "withholding_tax_slip_day": {
            "description": "Day for 源泉徴収票 submission (fixed: 31)",
            "example": 31,
            "maximum": 31,
            "minimum": 1,
            "nullable": true,
            "type": "integer"
          },
          "withholding_tax_slip_month": {
            "description": "Month for 源泉徴収票 submission (fixed: January)",
            "example": 1,
            "maximum": 12,
            "minimum": 1,
            "nullable": true,
            "type": "integer"
          },
          "year_end_adjustment_active": {
            "description": "Whether year-end adjustment reminders are active",
            "example": true,
            "type": "boolean"
          },
          "year_end_adjustment_day": {
            "description": "Day for year-end adjustment reminders (年末調整)",
            "example": 31,
            "maximum": 31,
            "minimum": 1,
            "nullable": true,
            "type": "integer"
          },
          "year_end_adjustment_month": {
            "description": "Month for year-end adjustment reminders",
            "example": 1,
            "maximum": 12,
            "minimum": 1,
            "nullable": true,
            "type": "integer"
          }
        },
        "required": [
          "id",
          "user_id",
          "reimbursement_active",
          "expense_payment_active",
          "invoice_active",
          "corporate_tax_active",
          "year_end_adjustment_active",
          "consumption_tax_active",
          "labor_insurance_active",
          "social_insurance_active",
          "legal_records_summary_active",
          "withholding_tax_slip_active",
          "salary_payment_report_active",
          "depreciable_assets_active",
          "final_tax_return_active",
          "created_at",
          "updated_at"
        ],
        "type": "object"
      },
      "ReminderConfigResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/ReminderConfig"
          },
          "message": {
            "example": "Reminder configs retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ReminderCycle": {
        "description": "Frequency cycle for reminder scheduling",
        "enum": [
          0,
          1,
          2
        ],
        "example": 0,
        "type": "integer",
        "x-enum-varnames": [
          "MONTHLY",
          "YEARLY",
          "WEEKLY"
        ]
      },
      "ReminderResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/Reminder"
          },
          "message": {
            "example": "Custom reminder created successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ReminderType": {
        "description": "Type of reminder for Japanese business operations.\n\n## Standard Reminder Types (0-8)\n- 0: REIMBURSEMENT - 経費精算 (Monthly expense reimbursement)\n- 1: EXPENSE_PAYMENT - 経費支払 (Monthly expense payment)\n- 2: INVOICE - 請求書 (Monthly invoice)\n- 3: CORPORATE_TAX - 法人税 (Fiscal year dependent)\n- 4: YEAR_END_ADJUSTMENT - 年末調整 (Fixed Dec/Jan) - 甲欄 users only\n- 5: CONSUMPTION_TAX - 消費税 (Fiscal year dependent)\n- 6: LABOR_INSURANCE - 労働保険 (Fixed Jun/Jul)\n- 7: SOCIAL_INSURANCE - 社会保険 (Fixed Jul)\n- 8: CUSTOM - カスタム (User-defined)\n\n## Fixed Calendar-Year Statutory Deadlines (9-12)\nThese are universal statutory deadlines that apply to ALL Japanese businesses and are fixed at January 31st:\n- 9: LEGAL_RECORDS_SUMMARY - 法定調書合計表 (e-Tax submission)\n- 10: WITHHOLDING_TAX_SLIP - 源泉徴収票提出 (e-Tax submission)\n- 11: SALARY_PAYMENT_REPORT - 給与支払報告書 (eLTAX submission)\n- 12: DEPRECIABLE_ASSETS - 償却資産申告 (eLTAX submission)\n\n## v4.43: 乙欄 User Specific (13)\n- 13: FINAL_TAX_RETURN - 確定申告 (March 15th deadline for 乙欄/secondary workplace users who cannot do 年末調整)",
        "enum": [
          0,
          1,
          2,
          3,
          4,
          5,
          6,
          7,
          8,
          9,
          10,
          11,
          12,
          13
        ],
        "example": 0,
        "type": "integer",
        "x-enum-varnames": [
          "REIMBURSEMENT",
          "EXPENSE_PAYMENT",
          "INVOICE",
          "CORPORATE_TAX",
          "YEAR_END_ADJUSTMENT",
          "CONSUMPTION_TAX",
          "LABOR_INSURANCE",
          "SOCIAL_INSURANCE",
          "CUSTOM",
          "LEGAL_RECORDS_SUMMARY",
          "WITHHOLDING_TAX_SLIP",
          "SALARY_PAYMENT_REPORT",
          "DEPRECIABLE_ASSETS",
          "FINAL_TAX_RETURN"
        ]
      },
      "RemindersListResponse": {
        "properties": {
          "data": {
            "items": {
              "$ref": "#/components/schemas/Reminder"
            },
            "type": "array"
          },
          "message": {
            "example": "Current reminders retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "RenameDocumentRequest": {
        "properties": {
          "document_name": {
            "description": "New document name (required)",
            "example": "Renamed Document",
            "minLength": 1,
            "type": "string"
          }
        },
        "required": [
          "document_name"
        ],
        "type": "object"
      },
      "ReopenPeriodRequest": {
        "properties": {
          "reason": {
            "description": "Reason for reopening the period",
            "example": "Additional adjustments required for year-end audit",
            "minLength": 1,
            "type": "string"
          }
        },
        "required": [
          "reason"
        ],
        "type": "object"
      },
      "RequestTraceResponse": {
        "properties": {
          "data": {
            "description": "Log entries for specific request",
            "items": {
              "$ref": "#/components/schemas/LogEntry"
            },
            "type": "array"
          },
          "message": {
            "example": "Found 5 log entries for request",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ResetProgressRequest": {
        "properties": {
          "company_id": {
            "description": "Optional company ID for multi-company progress reset",
            "example": "comp_123456",
            "type": "string"
          }
        },
        "type": "object"
      },
      "RestoreDocumentResponse": {
        "properties": {
          "data": {
            "properties": {
              "document_name": {
                "type": "string"
              },
              "id": {
                "format": "uuid",
                "type": "string"
              },
              "is_deleted": {
                "example": false,
                "type": "boolean"
              },
              "status": {
                "type": "string"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Document restored successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "type": "object"
      },
      "RetentionColumns": {
        "description": "Retention tracking columns added in v5.13. retention_end_date is auto-computed by trigger.",
        "properties": {
          "retention_end_date": {
            "description": "Auto-computed: retention_start_date + 7 years. Date after which record may be archived.",
            "format": "date",
            "nullable": true,
            "type": "string"
          },
          "retention_start_date": {
            "description": "Fiscal year end date when record was created. Retention runs 7 years from this date.",
            "format": "date",
            "nullable": true,
            "type": "string"
          }
        },
        "type": "object"
      },
      "RetentionPolicy": {
        "properties": {
          "archive_enabled": {
            "example": false,
            "type": "boolean"
          },
          "max_activities_per_user": {
            "example": 10000,
            "type": "integer"
          },
          "retention_days": {
            "example": 90,
            "type": "integer"
          }
        },
        "type": "object"
      },
      "ReviewRequiredAsset": {
        "description": "Fixed asset requiring manual review for 償却資産申告",
        "properties": {
          "acquisitionCost": {
            "example": 500000,
            "type": "number"
          },
          "acquisitionDate": {
            "example": 20250301,
            "type": "integer"
          },
          "classification": {
            "example": 9,
            "type": "integer"
          },
          "classificationName": {
            "example": "その他",
            "type": "string"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "name": {
            "example": "特殊設備",
            "type": "string"
          },
          "reviewCode": {
            "example": "REQUIRES_REVIEW",
            "type": "string"
          },
          "reviewReason": {
            "example": "その他資産 - 個別判断が必要",
            "type": "string"
          }
        },
        "type": "object"
      },
      "RiskLevel": {
        "description": "Risk assessment level",
        "enum": [
          "low",
          "medium",
          "high"
        ],
        "example": "medium",
        "type": "string"
      },
      "RuleFrequency": {
        "description": "Transaction frequency pattern",
        "enum": [
          "monthly",
          "yearly",
          "irregular"
        ],
        "example": "monthly",
        "type": "string"
      },
      "RunDemoProcessingRequest": {
        "properties": {
          "companyId": {
            "format": "uuid",
            "type": "string"
          },
          "documentsGenerated": {
            "items": {
              "properties": {
                "id": {
                  "type": "string"
                },
                "name": {
                  "type": "string"
                },
                "type": {
                  "example": "P&L",
                  "type": "string"
                },
                "url": {
                  "type": "string"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "durationMs": {
            "example": 2500,
            "type": "integer"
          },
          "errors": {
            "items": {
              "properties": {
                "code": {
                  "type": "string"
                },
                "message": {
                  "type": "string"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "journalEntryCount": {
            "example": 150,
            "type": "integer"
          },
          "sessionId": {
            "format": "uuid",
            "type": "string"
          },
          "sourceFileName": {
            "example": "bank_statement_2026.csv",
            "type": "string"
          },
          "sourceType": {
            "$ref": "#/components/schemas/DemoProcessingSourceType"
          },
          "success": {
            "example": true,
            "type": "boolean"
          },
          "warnings": {
            "items": {
              "properties": {
                "code": {
                  "type": "string"
                },
                "message": {
                  "type": "string"
                }
              },
              "type": "object"
            },
            "type": "array"
          }
        },
        "required": [
          "success"
        ],
        "type": "object"
      },
      "RunIntegrityCheckRequest": {
        "properties": {
          "bankTransactionIds": {
            "description": "Specific bank transaction IDs to check",
            "example": [
              "123e4567-e89b-12d3-a456-426614174000"
            ],
            "items": {
              "format": "uuid",
              "type": "string"
            },
            "type": "array"
          },
          "checkType": {
            "$ref": "#/components/schemas/IntegrityCheckType",
            "default": "comprehensive"
          },
          "fiscalYear": {
            "description": "Fiscal year period (Japanese format)",
            "example": "2025/02/16-2026/02/15",
            "type": "string"
          },
          "periodEnd": {
            "description": "End date in YYYYMMDD format",
            "example": 20240930,
            "type": "integer"
          },
          "periodStart": {
            "description": "Start date in YYYYMMDD format",
            "example": 20240401,
            "type": "integer"
          }
        },
        "type": "object"
      },
      "SSEAnalysisProgress": {
        "description": "Progress data sent via SSE during AI analysis",
        "properties": {
          "analysis_results": {
            "description": "Results for completed items",
            "items": {
              "properties": {
                "anomalies_count": {
                  "type": "integer"
                },
                "extracted_amount": {
                  "type": "number"
                },
                "extracted_vendor": {
                  "type": "string"
                },
                "item_id": {
                  "format": "uuid",
                  "type": "string"
                },
                "status": {
                  "type": "string"
                },
                "suggested_category": {
                  "type": "integer"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "analyzed_items": {
            "description": "Number of successfully analyzed items",
            "type": "integer"
          },
          "current_item": {
            "description": "Currently processing item",
            "properties": {
              "file_name": {
                "type": "string"
              },
              "id": {
                "format": "uuid",
                "type": "string"
              },
              "status": {
                "enum": [
                  "pending",
                  "analyzing",
                  "completed",
                  "failed",
                  "skipped"
                ],
                "type": "string"
              }
            },
            "type": "object"
          },
          "failed_items": {
            "description": "Number of failed items",
            "type": "integer"
          },
          "percent_complete": {
            "description": "Progress percentage (0-100)",
            "type": "integer"
          },
          "session_id": {
            "format": "uuid",
            "type": "string"
          },
          "status": {
            "enum": [
              "draft",
              "analyzing",
              "reviewed",
              "creating",
              "completed",
              "failed",
              "cancelled"
            ],
            "type": "string"
          },
          "total_items": {
            "description": "Total number of items to analyze",
            "type": "integer"
          }
        },
        "type": "object"
      },
      "SSECompletedEvent": {
        "description": "Completion event with full result",
        "properties": {
          "completedAt": {
            "format": "date-time",
            "type": "string"
          },
          "result": {
            "properties": {
              "content": {
                "additionalProperties": true,
                "description": "Generated document content (JSON)",
                "type": "object"
              },
              "documentType": {
                "example": "salary_slip",
                "type": "string"
              },
              "generatedAt": {
                "format": "date-time",
                "type": "string"
              }
            },
            "type": "object"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "type": "object"
      },
      "SSEErrorEvent": {
        "description": "Error event",
        "properties": {
          "code": {
            "example": "DOCUMENT_GENERATION_ERROR",
            "type": "string"
          },
          "error": {
            "example": "AI service timeout",
            "type": "string"
          },
          "failedAt": {
            "format": "date-time",
            "type": "string"
          },
          "success": {
            "example": false,
            "type": "boolean"
          }
        },
        "type": "object"
      },
      "SSEEvent": {
        "description": "Generic SSE event structure",
        "properties": {
          "data": {
            "description": "Event-specific payload",
            "type": "object"
          },
          "session_id": {
            "format": "uuid",
            "type": "string"
          },
          "timestamp": {
            "format": "date-time",
            "type": "string"
          },
          "type": {
            "enum": [
              "wizard.connected",
              "wizard.session_updated",
              "wizard.item_uploaded",
              "wizard.analysis_started",
              "wizard.analysis_progress",
              "wizard.analysis_completed",
              "wizard.analysis_failed",
              "wizard.document_creating",
              "wizard.document_created",
              "wizard.completed",
              "wizard.error"
            ],
            "type": "string"
          }
        },
        "type": "object"
      },
      "SSEProgressEvent": {
        "description": "Progress update event (0-100%)",
        "properties": {
          "message": {
            "description": "Human-readable progress message",
            "example": "Generating document structure...",
            "type": "string"
          },
          "progress": {
            "description": "Progress percentage",
            "example": 40,
            "maximum": 100,
            "minimum": 0,
            "type": "number"
          }
        },
        "type": "object"
      },
      "SSEStreamEvent": {
        "description": "Server-Sent Event following OpenAI semantic event pattern",
        "properties": {
          "data": {
            "additionalProperties": true,
            "description": "Event-specific payload",
            "type": "object"
          },
          "id": {
            "description": "Unique event identifier for reconnection support",
            "example": "ai_stream_abc123_1",
            "type": "string"
          },
          "timestamp": {
            "description": "ISO timestamp of the event",
            "example": "2026-01-09T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "type": {
            "description": "Event type following OpenAI semantic pattern",
            "enum": [
              "response.created",
              "response.in_progress",
              "response.output_text.delta",
              "response.progress",
              "response.completed",
              "response.failed",
              "heartbeat",
              "error"
            ],
            "example": "response.progress",
            "type": "string"
          }
        },
        "required": [
          "id",
          "type",
          "timestamp",
          "data"
        ],
        "type": "object"
      },
      "SalaryCalculationRequest": {
        "description": "Salary withholding calculation request (給与源泉計算リクエスト)",
        "properties": {
          "dependents": {
            "default": 0,
            "description": "扶養親族数 (over 7: the 7-person 税額 less 1,610円 per extra person)",
            "example": 2,
            "maximum": 20,
            "minimum": 0,
            "type": "integer"
          },
          "gross_salary": {
            "description": "支給額",
            "example": 350000,
            "minimum": 0,
            "type": "number"
          },
          "social_insurance": {
            "default": 0,
            "description": "社会保険料控除",
            "example": 50000,
            "minimum": 0,
            "type": "number"
          },
          "tax_column": {
            "description": "甲欄/乙欄",
            "enum": [
              "kou",
              "otsu"
            ],
            "example": "kou",
            "type": "string"
          },
          "year": {
            "description": "適用年度",
            "example": 2026,
            "type": "integer"
          }
        },
        "required": [
          "gross_salary",
          "tax_column"
        ],
        "type": "object"
      },
      "SalaryCalculationResult": {
        "description": "Salary withholding calculation result (給与源泉計算結果)",
        "properties": {
          "breakdown": {
            "properties": {
              "appliedRate": {
                "example": "甲欄・扶養2人",
                "type": "string"
              },
              "kouAmount": {
                "example": 4700,
                "nullable": true,
                "type": "integer"
              },
              "otsuAmount": {
                "nullable": true,
                "type": "integer"
              },
              "tableRow": {
                "example": "299,000円以上 302,000円未満",
                "nullable": true,
                "type": "string"
              },
              "taxTableVersion": {
                "example": "令和8年",
                "type": "string"
              }
            },
            "type": "object"
          },
          "calculation": {
            "properties": {
              "grossSalary": {
                "example": 350000,
                "type": "number"
              },
              "netSalary": {
                "description": "差引支給額",
                "example": 295300,
                "type": "number"
              },
              "socialInsurance": {
                "example": 50000,
                "type": "number"
              },
              "taxableIncome": {
                "description": "課税対象額",
                "example": 300000,
                "type": "number"
              },
              "withholdingTax": {
                "description": "源泉徴収税額",
                "example": 4700,
                "type": "number"
              }
            },
            "type": "object"
          },
          "validation": {
            "properties": {
              "isValid": {
                "example": true,
                "type": "boolean"
              },
              "warnings": {
                "items": {
                  "type": "string"
                },
                "type": "array"
              }
            },
            "type": "object"
          }
        },
        "type": "object"
      },
      "SalarySlipDocumentSummary": {
        "description": "A 給与明細書 reached by the chain walk (multi-hop: claims → salary). Present since Wave 9.5; documented here with the VR-08 additions.",
        "properties": {
          "attachmentCount": {
            "example": 0,
            "type": "integer"
          },
          "currency": {
            "example": "JPY",
            "type": "string"
          },
          "hasInkan": {
            "$ref": "#/components/schemas/DockHasInkan"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "isLinkedToClaims": {
            "type": "boolean"
          },
          "isLinkedToPayment": {
            "type": "boolean"
          },
          "linkedClaimsId": {
            "format": "uuid",
            "type": "string"
          },
          "name": {
            "example": "2026年4月給与明細書",
            "type": "string"
          },
          "reimbursementNetPay": {
            "description": "VR-08 (v5.20+). 差引支給額 — the taxable net pay PLUS the non-taxable reimbursement\nlines paid alongside it (所得税基本通達 9-5 keeps those out of `netPay`), falling back to the sum of\n`earnings[].amount` when the slip carries no net-pay key, and to the reimbursement total alone when it\ncarries neither. 0 when nothing is readable.\n\nThis is what the dock's 給与 card shows, so it must match the slip's own rendered total — the client used to\nderive it by fetching each slip.",
            "example": 130976,
            "type": "number"
          },
          "status": {
            "enum": [
              "draft",
              "published",
              "archived"
            ],
            "type": "string"
          },
          "totalAmount": {
            "example": 300000,
            "type": "number"
          },
          "type": {
            "example": "salary_slip",
            "type": "string"
          }
        },
        "required": [
          "id",
          "name",
          "type",
          "totalAmount",
          "currency",
          "status",
          "attachmentCount"
        ],
        "type": "object"
      },
      "SalesInvoice": {
        "properties": {
          "client_id": {
            "description": "Client identifier",
            "example": "abc12345-def6-7890-ghij-klmnopqrstuv",
            "format": "uuid",
            "type": "string"
          },
          "created_at": {
            "description": "Creation timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "document_id": {
            "description": "Associated document identifier",
            "example": "550e8400-e29b-41d4-a716-446655440000",
            "format": "uuid",
            "type": "string"
          },
          "due_date": {
            "description": "Due date as Unix timestamp",
            "example": 1643673600,
            "type": "integer"
          },
          "id": {
            "description": "Invoice unique identifier",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "invoice_number": {
            "description": "Invoice number",
            "example": "INV-2024-001",
            "nullable": true,
            "type": "string"
          },
          "issue_date": {
            "description": "Issue date as Unix timestamp",
            "example": 1640995200,
            "type": "integer"
          },
          "items": {
            "description": "Invoice line items",
            "items": {
              "$ref": "#/components/schemas/InvoiceItem"
            },
            "type": "array"
          },
          "notes": {
            "description": "Additional notes",
            "example": [
              "Payment due within 30 days",
              "Late payment fee may apply"
            ],
            "items": {
              "type": "string"
            },
            "nullable": true,
            "type": "array"
          },
          "order_number": {
            "description": "Related order number",
            "example": "ORD-2024-001",
            "nullable": true,
            "type": "string"
          },
          "payment_info": {
            "additionalProperties": true,
            "description": "Payment information",
            "example": {
              "accountName": "ヤマダ タロウ",
              "accountNumber": "1234567",
              "accountType": "普通",
              "bankName": "みずほ銀行",
              "branchName": "東京営業部"
            },
            "nullable": true,
            "type": "object"
          },
          "period_end": {
            "description": "Project period end as Unix timestamp",
            "example": 1643673600,
            "nullable": true,
            "type": "integer"
          },
          "period_start": {
            "description": "Project period start as Unix timestamp",
            "example": 1640995200,
            "nullable": true,
            "type": "integer"
          },
          "project_title": {
            "description": "Project title or description",
            "example": "E-commerce Website Development",
            "type": "string"
          },
          "quote_number": {
            "description": "Related quote number",
            "example": "QUO-2024-001",
            "nullable": true,
            "type": "string"
          },
          "subtotal": {
            "description": "Subtotal amount before tax",
            "example": 200000,
            "minimum": 0,
            "type": "number"
          },
          "tax": {
            "description": "Tax amount",
            "example": 20000,
            "minimum": 0,
            "type": "number"
          },
          "total": {
            "description": "Total amount including tax",
            "example": 220000,
            "minimum": 0,
            "type": "number"
          },
          "updated_at": {
            "description": "Last update timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "user_id": {
            "description": "User identifier",
            "example": "789e0123-e45b-67c8-d901-234567890123",
            "format": "uuid",
            "type": "string"
          }
        },
        "required": [
          "id",
          "document_id",
          "user_id",
          "client_id",
          "issue_date",
          "due_date",
          "project_title",
          "subtotal",
          "tax",
          "total",
          "items",
          "created_at",
          "updated_at"
        ],
        "type": "object"
      },
      "SalesInvoiceCreateResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/SalesInvoice"
          },
          "message": {
            "example": "Sales invoice created successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 201,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "SalesInvoiceDeleteResponse": {
        "properties": {
          "data": {
            "properties": {
              "deleted": {
                "example": true,
                "type": "boolean"
              },
              "id": {
                "example": "123e4567-e89b-12d3-a456-426614174000",
                "format": "uuid",
                "type": "string"
              }
            },
            "required": [
              "deleted",
              "id"
            ],
            "type": "object"
          },
          "message": {
            "example": "Sales invoice deleted successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "SalesInvoiceListResponse": {
        "properties": {
          "data": {
            "items": {
              "$ref": "#/components/schemas/SalesInvoice"
            },
            "type": "array"
          },
          "message": {
            "example": "Sales invoices retrieved successfully",
            "type": "string"
          },
          "pagination": {
            "$ref": "#/components/schemas/Pagination"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data",
          "pagination"
        ],
        "type": "object"
      },
      "SalesInvoiceResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/SalesInvoice"
          },
          "message": {
            "example": "Sales invoice retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "SalesWorkflowResponse": {
        "properties": {
          "data": {
            "properties": {
              "availableActions": {
                "items": {
                  "properties": {
                    "action": {
                      "example": "create_order",
                      "type": "string"
                    },
                    "enabled": {
                      "example": true,
                      "type": "boolean"
                    },
                    "label": {
                      "example": "Create Purchase Order",
                      "type": "string"
                    },
                    "label_ja": {
                      "example": "発注書を作成",
                      "type": "string"
                    },
                    "reason": {
                      "nullable": true,
                      "type": "string"
                    },
                    "target_type": {
                      "example": "purchase_order",
                      "type": "string"
                    }
                  },
                  "type": "object"
                },
                "type": "array"
              },
              "chain": {
                "description": "The full workflow chain — null for stages without linked documents",
                "properties": {
                  "delivery": {
                    "oneOf": [
                      {
                        "$ref": "#/components/schemas/WorkflowDocument"
                      },
                      {
                        "type": "null"
                      }
                    ]
                  },
                  "invoice": {
                    "oneOf": [
                      {
                        "$ref": "#/components/schemas/WorkflowDocument"
                      },
                      {
                        "type": "null"
                      }
                    ]
                  },
                  "order": {
                    "oneOf": [
                      {
                        "$ref": "#/components/schemas/WorkflowDocument"
                      },
                      {
                        "type": "null"
                      }
                    ]
                  },
                  "quotation": {
                    "oneOf": [
                      {
                        "$ref": "#/components/schemas/WorkflowDocument"
                      },
                      {
                        "type": "null"
                      }
                    ]
                  }
                },
                "type": "object"
              },
              "document": {
                "$ref": "#/components/schemas/WorkflowDocument"
              },
              "generatedAt": {
                "format": "date-time",
                "type": "string"
              },
              "links": {
                "items": {
                  "properties": {
                    "child_document": {
                      "$ref": "#/components/schemas/WorkflowDocument"
                    },
                    "created_at": {
                      "format": "date-time",
                      "type": "string"
                    },
                    "parent_document": {
                      "$ref": "#/components/schemas/WorkflowDocument"
                    },
                    "relationship_id": {
                      "format": "uuid",
                      "type": "string"
                    },
                    "relationship_type": {
                      "example": "quotation_to_order",
                      "type": "string"
                    }
                  },
                  "type": "object"
                },
                "type": "array"
              },
              "salesInvoice": {
                "description": "Sales invoice details (only when an invoice exists in the chain)",
                "nullable": true,
                "properties": {
                  "due_date": {
                    "example": 20260331,
                    "nullable": true,
                    "type": "integer"
                  },
                  "id": {
                    "format": "uuid",
                    "type": "string"
                  },
                  "invoice_number": {
                    "example": "INV-2026-001",
                    "nullable": true,
                    "type": "string"
                  },
                  "issue_date": {
                    "example": 20260215,
                    "nullable": true,
                    "type": "integer"
                  },
                  "payment_status": {
                    "example": "unpaid",
                    "nullable": true,
                    "type": "string"
                  },
                  "tax_amount": {
                    "example": 50000,
                    "nullable": true,
                    "type": "integer"
                  },
                  "total_amount": {
                    "example": 550000,
                    "nullable": true,
                    "type": "integer"
                  }
                },
                "type": "object"
              },
              "stage": {
                "description": "Current document stage in the sales workflow",
                "enum": [
                  "quotation",
                  "order",
                  "delivery",
                  "invoice",
                  "unknown"
                ],
                "example": "quotation",
                "type": "string"
              },
              "stageIndex": {
                "description": "0-based index (quotation=0, order=1, delivery=2, invoice=3)",
                "example": 0,
                "type": "integer"
              },
              "totalStages": {
                "example": 4,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Sales workflow retrieved successfully",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "type": "object"
      },
      "SanteiPrefill": {
        "properties": {
          "average": {
            "description": "報酬月額 over the months with 17+ 支払基礎日数",
            "nullable": true,
            "type": "integer"
          },
          "notes": {
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "rows": {
            "items": {
              "properties": {
                "amount": {
                  "example": 200000,
                  "nullable": true,
                  "type": "integer"
                },
                "basisDays": {
                  "example": 30,
                  "nullable": true,
                  "type": "integer"
                },
                "label": {
                  "example": "4月",
                  "type": "string"
                },
                "month": {
                  "enum": [
                    4,
                    5,
                    6
                  ],
                  "type": "integer"
                },
                "paymentDate": {
                  "format": "date",
                  "nullable": true,
                  "type": "string"
                },
                "source": {
                  "example": "給与明細（下書き）",
                  "type": "string"
                }
              },
              "required": [
                "month",
                "label",
                "paymentDate",
                "amount",
                "basisDays",
                "source"
              ],
              "type": "object"
            },
            "type": "array"
          },
          "total": {
            "nullable": true,
            "type": "integer"
          },
          "year": {
            "example": 2026,
            "type": "integer"
          }
        },
        "required": [
          "year",
          "rows",
          "total",
          "average",
          "notes"
        ],
        "type": "object"
      },
      "SaveProgressRequest": {
        "properties": {
          "completed_steps": {
            "description": "Array of completed step indices",
            "example": [
              0,
              1,
              2
            ],
            "items": {
              "maximum": 17,
              "minimum": 0,
              "type": "number"
            },
            "type": "array"
          },
          "current_step_index": {
            "description": "Current step index (0-17)",
            "example": 3,
            "maximum": 17,
            "minimum": 0,
            "type": "number"
          },
          "document_status": {
            "additionalProperties": {
              "$ref": "#/components/schemas/DocumentStatus"
            },
            "description": "Document generation status tracking",
            "example": {
              "articles_of_incorporation": {
                "document_type": "articles_of_incorporation",
                "generated_at": "2024-01-15T10:30:00Z",
                "status": "draft"
              }
            },
            "type": "object"
          },
          "last_updated_at": {
            "description": "Last update timestamp (optional)",
            "example": "2024-01-15T10:30:00Z",
            "format": "date-time",
            "type": "string"
          },
          "step_data": {
            "additionalProperties": true,
            "description": "Step-specific data and user inputs",
            "example": {
              "BUSINESS_PURPOSE": {
                "purposes": [
                  "ソフトウェア開発",
                  "システム設計"
                ]
              },
              "COMPANY_TYPE": {
                "reasoning": "Better for funding",
                "selected_type": "kk"
              }
            },
            "type": "object"
          },
          "step_time_tracking": {
            "additionalProperties": {
              "$ref": "#/components/schemas/StepTimeTracking"
            },
            "description": "Time tracking for each step",
            "example": {
              "step_0": {
                "completed_at": "2024-01-15T10:30:00Z",
                "started_at": "2024-01-15T10:00:00Z",
                "time_spent_ms": 1800000
              }
            },
            "type": "object"
          },
          "user_context": {
            "additionalProperties": true,
            "description": "Flexible user context object (can be empty)",
            "example": {
              "business_purpose": "ソフトウェアの開発、販売及び保守",
              "business_type": "IT",
              "company_type": "kk"
            },
            "type": "object"
          }
        },
        "type": "object"
      },
      "ScrapeCompanyDataQuery": {
        "properties": {
          "corporate_number": {
            "description": "Japanese corporate number (13 digits, with or without T prefix)",
            "example": "1234567890123",
            "pattern": "^T?\\d{13}$",
            "type": "string"
          }
        },
        "required": [
          "corporate_number"
        ],
        "type": "object"
      },
      "SearchActivityRequest": {
        "description": "Search filter for activities. Use camelCase for all fields.",
        "properties": {
          "actionTypes": {
            "items": {
              "enum": [
                "document_view",
                "document_edit",
                "document_create",
                "document_delete",
                "document_generate",
                "document_download",
                "document_print",
                "document_send",
                "document_share",
                "document_sign",
                "document_stamp",
                "document_archive",
                "document_restore",
                "document_duplicate",
                "document_update",
                "document_lock",
                "document_unlock",
                "document_void",
                "settings_company",
                "settings_accounting",
                "settings_auth",
                "settings_inkan",
                "settings_signature",
                "settings_profile",
                "settings_notification",
                "settings_payment",
                "settings_integration",
                "settings_export",
                "settings_import",
                "journal_entry",
                "journal_view",
                "journal_delete",
                "journal_approve",
                "journal_reject",
                "bank_reconcile",
                "fiscal_period",
                "account_create",
                "account_edit",
                "account_delete",
                "account_view",
                "trial_balance_view",
                "trial_balance_export",
                "report_view",
                "report_generate",
                "report_export",
                "report_print",
                "report_schedule",
                "client_create",
                "client_edit",
                "client_delete",
                "client_view",
                "ai_chat",
                "ai_suggestion_accept",
                "ai_suggestion_reject",
                "ai_reconcile",
                "ai_analyze",
                "page_visit",
                "session_start",
                "session_end",
                "session_resume",
                "tab_switch",
                "modal_open",
                "modal_close",
                "search_execute",
                "filter_apply",
                "sort_change",
                "form_submit",
                "form_save_draft",
                "form_validation_error",
                "error_occurred",
                "api_error",
                "network_error",
                "login",
                "logout",
                "password_change",
                "mfa_enable",
                "mfa_disable",
                "bulk_upload",
                "bulk_delete",
                "csv_import",
                "csv_export",
                "other"
              ],
              "type": "string"
            },
            "type": "array"
          },
          "entityType": {
            "type": "string"
          },
          "errorsOnly": {
            "type": "boolean"
          },
          "fromDate": {
            "format": "date-time",
            "type": "string"
          },
          "limit": {
            "default": 10,
            "maximum": 100,
            "minimum": 1,
            "type": "integer"
          },
          "offset": {
            "default": 0,
            "minimum": 0,
            "type": "integer"
          },
          "routeContains": {
            "type": "string"
          },
          "sessionId": {
            "type": "string"
          },
          "toDate": {
            "format": "date-time",
            "type": "string"
          }
        },
        "type": "object"
      },
      "SearchGroup": {
        "properties": {
          "items": {
            "items": {
              "$ref": "#/components/schemas/SearchHit"
            },
            "type": "array"
          },
          "label": {
            "enum": [
              "書類",
              "ファイル",
              "経費",
              "銀行取引",
              "仕訳",
              "取引先"
            ],
            "type": "string"
          },
          "more": {
            "description": "More hits exist than `limit`.",
            "type": "boolean"
          },
          "type": {
            "enum": [
              "file",
              "document",
              "expense",
              "bank_transaction",
              "journal_entry",
              "client"
            ],
            "type": "string"
          }
        },
        "required": [
          "type",
          "label",
          "items",
          "more"
        ],
        "type": "object"
      },
      "SearchHit": {
        "properties": {
          "amountYen": {
            "example": 1234,
            "nullable": true,
            "type": "number"
          },
          "date": {
            "example": "2026-07-31",
            "format": "date",
            "nullable": true,
            "type": "string"
          },
          "documentType": {
            "example": "claims",
            "nullable": true,
            "type": "string"
          },
          "fileId": {
            "description": "For files, and for expense lines with a receipt.",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "href": {
            "description": "Server-built FE route: /files?file=, /view/<document-type>/<id>, /bank-statement?tab=transactions&panelTx=, /tax-journal?jeId=&highlight=&entryDate=, /trading-partners?client=, or /expense-reports.",
            "example": "/view/claims/00000000-0000-4000-8000-000000000001",
            "type": "string"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "snippet": {
            "description": "The matched words in context; null when the title shows them.",
            "maxLength": 120,
            "nullable": true,
            "type": "string"
          },
          "subtitle": {
            "description": "取引先・品目・書類の種類",
            "example": "指定ゴミ袋",
            "nullable": true,
            "type": "string"
          },
          "title": {
            "description": "What the owner calls it: file / 書類 name, payee, bank description, 摘要, client name.",
            "example": "テスト商店 本店",
            "type": "string"
          },
          "trail": {
            "description": "What to pass to GET /api/money-trail; null for 仕訳 and 取引先.",
            "nullable": true,
            "properties": {
              "id": {
                "format": "uuid",
                "type": "string"
              },
              "kind": {
                "enum": [
                  "file",
                  "document",
                  "bank_transaction",
                  "expense"
                ],
                "type": "string"
              }
            },
            "required": [
              "kind",
              "id"
            ],
            "type": "object"
          },
          "type": {
            "enum": [
              "file",
              "document",
              "expense",
              "bank_transaction",
              "journal_entry",
              "client"
            ],
            "type": "string"
          }
        },
        "required": [
          "type",
          "id",
          "title",
          "subtitle",
          "date",
          "amountYen",
          "href",
          "snippet",
          "documentType",
          "fileId",
          "trail"
        ],
        "type": "object"
      },
      "SearchResponse": {
        "properties": {
          "folded": {
            "description": "The query after the kana/width/case fold.",
            "example": "ごみ袋",
            "type": "string"
          },
          "groups": {
            "description": "Non-empty groups only, in the order 書類, ファイル, 経費, 銀行取引, 仕訳, 取引先.",
            "items": {
              "$ref": "#/components/schemas/SearchGroup"
            },
            "type": "array"
          },
          "query": {
            "example": "ゴミ袋",
            "type": "string"
          },
          "relaxed": {
            "description": "True when the exact query matched nothing and the hits match its words instead: 「市内指定ごみ袋」 → 市内 · 指定 · ごみ袋, and a typed question → its subject without the grammar (「テスト商店で買ったものは？」 → てすと · 商店).",
            "type": "boolean"
          }
        },
        "required": [
          "query",
          "folded",
          "relaxed",
          "groups"
        ],
        "type": "object"
      },
      "SearchResult": {
        "properties": {
          "article": {
            "$ref": "#/components/schemas/KnowledgeArticle"
          },
          "matchedTerms": {
            "example": [
              "消耗品",
              "経費"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "relevanceScore": {
            "example": 15,
            "type": "number"
          }
        },
        "type": "object"
      },
      "SearchScope": {
        "properties": {
          "dateRange": {
            "$ref": "#/components/schemas/DateRange"
          },
          "documentTypes": {
            "description": "Document types to search",
            "items": {
              "$ref": "#/components/schemas/DocumentType"
            },
            "type": "array"
          }
        },
        "type": "object"
      },
      "SecurityScoreResponse": {
        "properties": {
          "data": {
            "properties": {
              "backupEmailVerified": {
                "type": "boolean"
              },
              "hasBackupEmail": {
                "type": "boolean"
              },
              "hasRecoveryCodes": {
                "type": "boolean"
              },
              "linkedAccounts": {
                "example": [
                  "google"
                ],
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              "recoveryCodesRemaining": {
                "type": "integer"
              },
              "score": {
                "description": "1=基本, 2=普通, 3=安全",
                "enum": [
                  1,
                  2,
                  3
                ],
                "type": "integer"
              }
            },
            "type": "object"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "type": "object"
      },
      "SentryTunnelError": {
        "properties": {
          "code": {
            "example": "SENTRY_TUNNEL_RATE_LIMITED",
            "type": "string"
          },
          "message": {
            "type": "string"
          },
          "reason": {
            "description": "Parse/allowlist failure reason when status is 400",
            "enum": [
              "empty_envelope",
              "invalid_envelope_header",
              "missing_dsn",
              "invalid_dsn",
              "host_not_allowed",
              "project_not_allowed"
            ],
            "type": "string"
          },
          "success": {
            "example": false,
            "type": "boolean"
          }
        },
        "type": "object"
      },
      "SessionJobsResponse": {
        "properties": {
          "data": {
            "items": {
              "$ref": "#/components/schemas/ImageProcessingJob"
            },
            "type": "array"
          },
          "message": {
            "example": "Session jobs retrieved successfully",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "SessionProgress": {
        "properties": {
          "completedFiles": {
            "description": "Number of successfully completed files",
            "example": 6,
            "type": "integer"
          },
          "failedFiles": {
            "description": "Number of failed files",
            "example": 1,
            "type": "integer"
          },
          "isComplete": {
            "description": "Whether all files in session are processed",
            "example": false,
            "type": "boolean"
          },
          "processedFiles": {
            "description": "Number of processed files",
            "example": 7,
            "type": "integer"
          },
          "progressPercentage": {
            "description": "Overall session progress percentage",
            "example": 70,
            "maximum": 100,
            "minimum": 0,
            "type": "number"
          },
          "sessionId": {
            "description": "Session identifier",
            "example": "session_1705312200000_abc123def",
            "type": "string"
          },
          "totalFiles": {
            "description": "Total number of files in session",
            "example": 10,
            "type": "integer"
          }
        },
        "required": [
          "sessionId",
          "totalFiles",
          "processedFiles",
          "completedFiles",
          "failedFiles",
          "progressPercentage",
          "isComplete"
        ],
        "type": "object"
      },
      "SessionProgressResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/SessionProgress"
          },
          "message": {
            "example": "Session progress retrieved successfully",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "SessionResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/SimulationSession"
          },
          "message": {
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "type": "object"
      },
      "SessionSummary": {
        "properties": {
          "activity_count": {
            "type": "integer"
          },
          "browser": {
            "nullable": true,
            "type": "string"
          },
          "device_type": {
            "nullable": true,
            "type": "string"
          },
          "duration_ms": {
            "nullable": true,
            "type": "integer"
          },
          "ended_at": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "error_count": {
            "type": "integer"
          },
          "os": {
            "nullable": true,
            "type": "string"
          },
          "routes_visited": {
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "session_id": {
            "type": "string"
          },
          "started_at": {
            "format": "date-time",
            "type": "string"
          }
        },
        "type": "object"
      },
      "SettlePayoutResult": {
        "properties": {
          "feeJournalEntryId": {
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "feeTransactionId": {
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "journalEntryCreated": {
            "type": "boolean"
          },
          "journalEntryId": {
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "paySlipsMarkedPaid": {
            "type": "integer"
          },
          "payouts": {
            "items": {
              "properties": {
                "paidAmount": {
                  "type": "integer"
                },
                "paymentDocumentId": {
                  "format": "uuid",
                  "type": "string"
                },
                "remainingAmount": {
                  "type": "integer"
                },
                "status": {
                  "enum": [
                    "scheduled",
                    "partially_paid",
                    "paid"
                  ],
                  "type": "string"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "replay": {
            "type": "boolean"
          },
          "settledClaims": {
            "items": {
              "properties": {
                "amount": {
                  "type": "integer"
                },
                "documentId": {
                  "format": "uuid",
                  "type": "string"
                },
                "documentName": {
                  "nullable": true,
                  "type": "string"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "success": {
            "type": "boolean"
          },
          "totalAmount": {
            "type": "integer"
          },
          "transferTransactionId": {
            "format": "uuid",
            "type": "string"
          },
          "warnings": {
            "items": {
              "type": "string"
            },
            "type": "array"
          }
        },
        "type": "object"
      },
      "SettlementPackCandidate": {
        "properties": {
          "allowanceAmount": {
            "type": "integer"
          },
          "amount": {
            "type": "integer"
          },
          "displayTitle": {
            "description": "What the claim is for, derived from its content; the stored name is unchanged",
            "example": "高原拠点 · 消耗品費/会議費 21件",
            "nullable": true,
            "type": "string"
          },
          "documentDate": {
            "nullable": true,
            "type": "integer"
          },
          "documentId": {
            "format": "uuid",
            "type": "string"
          },
          "documentName": {
            "nullable": true,
            "type": "string"
          },
          "expenseAmount": {
            "type": "integer"
          },
          "priorFiscalYear": {
            "description": "Dated before the current fiscal year — may have been settled outside SBC",
            "type": "boolean"
          }
        },
        "type": "object"
      },
      "SettlementPackCreateResult": {
        "properties": {
          "integrityUnchanged": {
            "type": "boolean"
          },
          "items": {
            "items": {
              "$ref": "#/components/schemas/SettlementPackItem"
            },
            "type": "array"
          },
          "linkIds": {
            "items": {
              "format": "uuid",
              "type": "string"
            },
            "type": "array"
          },
          "paymentDocumentId": {
            "format": "uuid",
            "type": "string"
          },
          "proposedName": {
            "type": "string"
          },
          "reused": {
            "type": "boolean"
          },
          "success": {
            "type": "boolean"
          },
          "totalAmount": {
            "type": "integer"
          },
          "warnings": {
            "items": {
              "type": "string"
            },
            "type": "array"
          }
        },
        "type": "object"
      },
      "SettlementPackItem": {
        "properties": {
          "allowanceAmount": {
            "type": "integer"
          },
          "amount": {
            "type": "integer"
          },
          "expenseAmount": {
            "type": "integer"
          },
          "sourceDocumentId": {
            "format": "uuid",
            "type": "string"
          },
          "sourceDocumentName": {
            "nullable": true,
            "type": "string"
          }
        },
        "type": "object"
      },
      "SettlementPackPreview": {
        "properties": {
          "alreadyExists": {
            "type": "boolean"
          },
          "existingPaymentId": {
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "items": {
            "items": {
              "$ref": "#/components/schemas/SettlementPackItem"
            },
            "type": "array"
          },
          "payDate": {
            "example": "2026-08-25",
            "type": "string"
          },
          "proposedName": {
            "type": "string"
          },
          "totalAmount": {
            "type": "integer"
          },
          "warnings": {
            "items": {
              "type": "string"
            },
            "type": "array"
          }
        },
        "type": "object"
      },
      "ShatakuProperty": {
        "properties": {
          "address": {
            "type": "string"
          },
          "created_at": {
            "format": "date-time",
            "type": "string"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "name": {
            "example": "本社近郊マンション 101",
            "type": "string"
          },
          "occupant_type": {
            "enum": [
              "director",
              "employee"
            ],
            "type": "string"
          },
          "verificationStatus": {
            "enum": [
              "pending",
              "partial",
              "complete"
            ],
            "type": "string"
          }
        },
        "type": "object"
      },
      "Signature": {
        "properties": {
          "created_at": {
            "format": "date-time",
            "type": "string"
          },
          "description": {
            "example": "My primary handwritten signature",
            "nullable": true,
            "type": "string"
          },
          "file_hash": {
            "description": "SHA-256 hash for integrity verification",
            "nullable": true,
            "type": "string"
          },
          "file_name": {
            "example": "my_signature.png",
            "type": "string"
          },
          "file_size": {
            "example": 45678,
            "nullable": true,
            "type": "integer"
          },
          "file_url": {
            "example": "user-id/handwritten_1234567890_signature.png",
            "type": "string"
          },
          "id": {
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "is_active": {
            "example": true,
            "type": "boolean"
          },
          "is_default": {
            "example": true,
            "type": "boolean"
          },
          "mime_type": {
            "example": "image/png",
            "nullable": true,
            "type": "string"
          },
          "name": {
            "example": "Handwritten Signature - 01/07/2026",
            "type": "string"
          },
          "signature_type": {
            "enum": [
              "handwritten",
              "digital",
              "initials"
            ],
            "example": "handwritten",
            "type": "string"
          },
          "signed_url": {
            "description": "Time-limited signed URL (1-hour expiry)",
            "nullable": true,
            "type": "string"
          },
          "updated_at": {
            "format": "date-time",
            "type": "string"
          }
        },
        "type": "object"
      },
      "SignatureUpdateRequest": {
        "properties": {
          "description": {
            "maxLength": 500,
            "type": "string"
          },
          "is_default": {
            "type": "boolean"
          },
          "name": {
            "maxLength": 255,
            "type": "string"
          }
        },
        "type": "object"
      },
      "SignatureUploadRequest": {
        "properties": {
          "description": {
            "description": "Optional description",
            "maxLength": 500,
            "type": "string"
          },
          "file": {
            "description": "Image file (JPEG, PNG, GIF, WebP, SVG)",
            "format": "binary",
            "type": "string"
          },
          "is_default": {
            "description": "Set as default signature for this type",
            "type": "boolean"
          },
          "name": {
            "description": "Signature name (auto-generated if not provided)",
            "maxLength": 255,
            "type": "string"
          }
        },
        "required": [
          "file"
        ],
        "type": "object"
      },
      "SignaturesForDocument": {
        "properties": {
          "default_url": {
            "description": "Signed URL for overall default signature",
            "nullable": true,
            "type": "string"
          },
          "digital_url": {
            "description": "Signed URL for default digital signature",
            "nullable": true,
            "type": "string"
          },
          "handwritten_url": {
            "description": "Signed URL for default handwritten signature",
            "nullable": true,
            "type": "string"
          },
          "initials_url": {
            "description": "Signed URL for default initials",
            "nullable": true,
            "type": "string"
          }
        },
        "type": "object"
      },
      "SimplifiedTaxationCalculation": {
        "properties": {
          "deemedInputTax": {
            "description": "Deemed input tax (みなし仮払消費税)",
            "example": 275000,
            "format": "decimal",
            "type": "number"
          },
          "deemedPurchaseRate": {
            "description": "Deemed purchase rate (みなし仕入率)",
            "example": 0.5,
            "format": "decimal",
            "type": "number"
          },
          "outputTax": {
            "description": "Total output tax (仮受消費税合計)",
            "example": 550000,
            "format": "decimal",
            "type": "number"
          },
          "taxDue": {
            "description": "Tax due amount (納付税額)",
            "example": 275000,
            "format": "decimal",
            "type": "number"
          }
        },
        "required": [
          "outputTax",
          "deemedPurchaseRate",
          "deemedInputTax",
          "taxDue"
        ],
        "type": "object"
      },
      "SimplifiedTaxationEligibility": {
        "properties": {
          "basePeriodSales": {
            "description": "Base period taxable sales amount",
            "example": 30000000,
            "format": "decimal",
            "type": "number"
          },
          "isEligible": {
            "description": "Whether eligible for simplified taxation",
            "example": true,
            "type": "boolean"
          },
          "locks": {
            "description": "簡易課税制度選択届出書を出せない期間（高額特定資産, 消費税法37条3項）. `blocked` makes isEligible false; `check` depends on whether the ledger cost is 税抜.",
            "items": {
              "properties": {
                "asset": {
                  "properties": {
                    "acquiredOn": {
                      "description": "YYYYMMDD",
                      "type": "integer"
                    },
                    "costYen": {
                      "type": "number"
                    },
                    "name": {
                      "type": "string"
                    }
                  },
                  "type": "object"
                },
                "canFileFrom": {
                  "description": "YYYYMMDD — the 届出書 can be filed from this day",
                  "type": "integer"
                },
                "certainty": {
                  "enum": [
                    "blocked",
                    "check"
                  ],
                  "type": "string"
                },
                "earliestEffectiveFrom": {
                  "description": "YYYYMMDD — earliest 課税期間 簡易課税 can apply",
                  "type": "integer"
                },
                "kind": {
                  "enum": [
                    "high_value_asset"
                  ],
                  "type": "string"
                },
                "lockedFrom": {
                  "description": "YYYYMMDD — first day of the 課税期間 the asset was taken in",
                  "type": "integer"
                },
                "reasonJa": {
                  "type": "string"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "reason": {
            "description": "Detailed explanation of eligibility status",
            "example": "基準期間（2022年）の課税売上高が5,000万円以下のため、簡易課税を選択できます",
            "type": "string"
          },
          "threshold": {
            "description": "Eligibility threshold (¥50,000,000)",
            "example": 50000000,
            "format": "decimal",
            "type": "number"
          }
        },
        "required": [
          "isEligible",
          "basePeriodSales",
          "threshold",
          "reason"
        ],
        "type": "object"
      },
      "SimulationDataSource": {
        "description": "Source of simulation data",
        "enum": [
          "simulation",
          "company",
          "template"
        ],
        "example": "simulation",
        "type": "string"
      },
      "SimulationSession": {
        "properties": {
          "companyId": {
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "createdAt": {
            "format": "date-time",
            "type": "string"
          },
          "dataSource": {
            "$ref": "#/components/schemas/SimulationDataSource"
          },
          "description": {
            "nullable": true,
            "type": "string"
          },
          "financialData": {
            "type": "object"
          },
          "fiscalYear": {
            "nullable": true,
            "type": "string"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "isActive": {
            "type": "boolean"
          },
          "name": {
            "nullable": true,
            "type": "string"
          },
          "templateId": {
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "transactions": {
            "items": {
              "$ref": "#/components/schemas/SimulationTransaction"
            },
            "type": "array"
          },
          "updatedAt": {
            "format": "date-time",
            "type": "string"
          },
          "userId": {
            "format": "uuid",
            "type": "string"
          },
          "version": {
            "type": "integer"
          }
        },
        "type": "object"
      },
      "SimulationTemplate": {
        "properties": {
          "category": {
            "$ref": "#/components/schemas/SimulationTemplateCategory"
          },
          "createdAt": {
            "format": "date-time",
            "type": "string"
          },
          "description": {
            "type": "string"
          },
          "displayOrder": {
            "type": "integer"
          },
          "financialData": {
            "description": "Pre-populated balance sheet, P&L, and cash flow data",
            "type": "object"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "isActive": {
            "type": "boolean"
          },
          "name": {
            "example": "スタートアップ企業向けテンプレート",
            "type": "string"
          },
          "templateId": {
            "example": "startup-template",
            "type": "string"
          },
          "transactionTemplates": {
            "items": {
              "$ref": "#/components/schemas/TransactionTemplateItem"
            },
            "type": "array"
          },
          "updatedAt": {
            "format": "date-time",
            "type": "string"
          }
        },
        "type": "object"
      },
      "SimulationTemplateCategory": {
        "description": "Template category",
        "enum": [
          "startup",
          "small_business",
          "corporate",
          "custom"
        ],
        "example": "startup",
        "type": "string"
      },
      "SimulationTransaction": {
        "properties": {
          "amount": {
            "type": "number"
          },
          "appliedAt": {
            "format": "date-time",
            "type": "string"
          },
          "createdAt": {
            "format": "date-time",
            "type": "string"
          },
          "creditAccount": {
            "type": "string"
          },
          "debitAccount": {
            "type": "string"
          },
          "description": {
            "nullable": true,
            "type": "string"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "isHidden": {
            "type": "boolean"
          },
          "metadata": {
            "type": "object"
          },
          "name": {
            "type": "string"
          },
          "sequenceNumber": {
            "type": "integer"
          },
          "templateId": {
            "type": "string"
          }
        },
        "type": "object"
      },
      "SingleProviderModelsResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/ProviderModelsResult"
          },
          "message": {
            "example": "OpenAI models retrieved successfully",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "SoftDeleteColumns": {
        "description": "Soft-delete columns added to core financial tables in v5.13 for 電子帳簿保存法 compliance.",
        "properties": {
          "deleted_at": {
            "description": "Soft-delete timestamp. Records within retention period must never be hard-deleted.",
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "deletion_reason": {
            "description": "Required reason for deletion/correction per Electronic Bookkeeping Act.",
            "nullable": true,
            "type": "string"
          }
        },
        "type": "object"
      },
      "SpecialRule20Calculation": {
        "properties": {
          "outputTax": {
            "description": "Total output tax (仮受消費税合計)",
            "example": 550000,
            "format": "decimal",
            "type": "number"
          },
          "taxDue": {
            "description": "Tax due amount - 20% of output tax (納付税額)",
            "example": 110000,
            "format": "decimal",
            "type": "number"
          }
        },
        "required": [
          "outputTax",
          "taxDue"
        ],
        "type": "object"
      },
      "SplitMatchResult": {
        "properties": {
          "amountMatch": {
            "description": "Whether amounts match exactly",
            "example": true,
            "type": "boolean"
          },
          "documents": {
            "description": "Documents in split match",
            "items": {
              "properties": {
                "amount": {
                  "example": 8000,
                  "format": "decimal",
                  "type": "number"
                },
                "documentId": {
                  "example": "doc_123",
                  "type": "string"
                },
                "matchScore": {
                  "example": 0.85,
                  "format": "double",
                  "type": "number"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "enabled": {
            "description": "Whether split matching is enabled",
            "example": true,
            "type": "boolean"
          },
          "totalAmount": {
            "description": "Total amount of matched documents",
            "example": 15000,
            "format": "decimal",
            "type": "number"
          },
          "transactionAmount": {
            "description": "Original transaction amount",
            "example": 15000,
            "format": "decimal",
            "type": "number"
          }
        },
        "required": [
          "enabled",
          "documents",
          "totalAmount",
          "transactionAmount",
          "amountMatch"
        ],
        "type": "object"
      },
      "StartGoalRequest": {
        "properties": {
          "goal_id": {
            "example": "setup_company",
            "maxLength": 50,
            "type": "string"
          }
        },
        "required": [
          "goal_id"
        ],
        "type": "object"
      },
      "StatutoryTaskMetadata": {
        "description": "Metadata for a statutory task type",
        "properties": {
          "actions": {
            "items": {
              "properties": {
                "actionLabel": {
                  "type": "string"
                },
                "actionType": {
                  "type": "string"
                },
                "conditionKey": {
                  "nullable": true,
                  "type": "string"
                },
                "conditionLabel": {
                  "nullable": true,
                  "type": "string"
                },
                "displayOrder": {
                  "type": "integer"
                },
                "id": {
                  "format": "uuid",
                  "type": "string"
                },
                "isRequired": {
                  "type": "boolean"
                },
                "methodLabel": {
                  "nullable": true,
                  "type": "string"
                },
                "recipientLabel": {
                  "type": "string"
                },
                "recipientType": {
                  "type": "string"
                },
                "submissionMethod": {
                  "nullable": true,
                  "type": "string"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "description": {
            "example": "給与所得の源泉徴収票",
            "type": "string"
          },
          "shortTitle": {
            "example": "源泉徴収票",
            "type": "string"
          },
          "title": {
            "example": "源泉徴収票",
            "type": "string"
          }
        },
        "type": "object"
      },
      "StatutoryTaskMetadataResponse": {
        "properties": {
          "data": {
            "additionalProperties": {
              "$ref": "#/components/schemas/StatutoryTaskMetadata"
            },
            "description": "Map of reminder_type to task metadata",
            "type": "object"
          },
          "message": {
            "example": "Statutory task metadata retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "StepGuidanceAPIResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/StepGuidanceResponse"
          },
          "message": {
            "example": "ステップガイダンスを生成しました",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "StepGuidanceRequest": {
        "properties": {
          "step": {
            "$ref": "#/components/schemas/EstablishmentStep"
          },
          "suggestionContext": {
            "$ref": "#/components/schemas/SuggestionContext"
          },
          "suggestionType": {
            "$ref": "#/components/schemas/SuggestionType"
          },
          "userContext": {
            "properties": {
              "businessType": {
                "description": "Type of business",
                "example": "IT",
                "type": "string"
              },
              "companyType": {
                "$ref": "#/components/schemas/CompanyType"
              }
            },
            "type": "object"
          },
          "userQuestion": {
            "description": "Specific user question about the step",
            "example": "資本金はいくらにすべきですか？",
            "maxLength": 2000,
            "type": "string"
          }
        },
        "required": [
          "step"
        ],
        "type": "object"
      },
      "StepGuidanceResponse": {
        "properties": {
          "confidence": {
            "$ref": "#/components/schemas/ConfidenceLevel"
          },
          "estimatedCost": {
            "description": "Estimated cost for this step",
            "example": "無料（自分で作成する場合）",
            "type": "string"
          },
          "estimatedTime": {
            "description": "Estimated time to complete this step",
            "example": "1-2日",
            "type": "string"
          },
          "nextSteps": {
            "description": "Recommended next steps",
            "example": [
              "具体的な事業内容を整理する",
              "将来の事業拡張計画を検討する",
              "類似企業の事業目的を参考にする"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "reasoning": {
            "description": "Detailed reasoning behind the recommendation",
            "example": "IT事業では技術の進歩が早いため、柔軟性のある事業目的の記載が重要です。",
            "type": "string"
          },
          "recommendation": {
            "description": "AI recommendation for the step",
            "example": "事業目的は具体的かつ将来の事業拡張を考慮して記載することをお勧めします。",
            "type": "string"
          },
          "warnings": {
            "description": "Important warnings or considerations",
            "example": [
              "事業目的が曖昧すぎると登記で問題になる可能性があります"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          }
        },
        "required": [
          "recommendation",
          "reasoning",
          "confidence",
          "nextSteps",
          "warnings",
          "estimatedTime",
          "estimatedCost"
        ],
        "type": "object"
      },
      "StepMetadata": {
        "properties": {
          "category": {
            "description": "Step category",
            "example": "事前準備",
            "type": "string"
          },
          "description": {
            "description": "Step description",
            "example": "定款に記載する事業目的を決定",
            "type": "string"
          },
          "estimatedCost": {
            "description": "Estimated cost",
            "example": "無料",
            "type": "string"
          },
          "estimatedTime": {
            "description": "Estimated time to complete",
            "example": "1-3日",
            "type": "string"
          },
          "id": {
            "description": "Step index (0-17)",
            "example": 1,
            "type": "number"
          },
          "key": {
            "$ref": "#/components/schemas/EstablishmentStep"
          },
          "title": {
            "description": "Step title in English",
            "example": "Business Purpose",
            "type": "string"
          },
          "titleJa": {
            "description": "Step title in Japanese",
            "example": "事業目的の決定",
            "type": "string"
          }
        },
        "required": [
          "id",
          "key",
          "title",
          "titleJa",
          "description",
          "category",
          "estimatedTime",
          "estimatedCost"
        ],
        "type": "object"
      },
      "StepQuestion": {
        "properties": {
          "id": {
            "description": "Question identifier",
            "example": "business_type",
            "type": "string"
          },
          "options": {
            "description": "Available options (for single/multi choice questions)",
            "items": {
              "$ref": "#/components/schemas/QuestionOption"
            },
            "type": "array"
          },
          "question": {
            "description": "Question text",
            "example": "主な事業内容は何ですか？",
            "type": "string"
          },
          "type": {
            "description": "Question type",
            "enum": [
              "single",
              "multi",
              "text",
              "number"
            ],
            "example": "single",
            "type": "string"
          }
        },
        "required": [
          "id",
          "question",
          "type"
        ],
        "type": "object"
      },
      "StepQuestionsAPIResponse": {
        "properties": {
          "data": {
            "items": {
              "$ref": "#/components/schemas/StepQuestion"
            },
            "type": "array"
          },
          "message": {
            "example": "ステップの質問を生成しました",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "StepQuestionsRequest": {
        "properties": {
          "step": {
            "$ref": "#/components/schemas/EstablishmentStep"
          }
        },
        "required": [
          "step"
        ],
        "type": "object"
      },
      "StepTimeTracking": {
        "properties": {
          "completed_at": {
            "description": "Step completion timestamp",
            "example": "2024-01-15T10:30:00Z",
            "format": "date-time",
            "type": "string"
          },
          "started_at": {
            "description": "Step start timestamp",
            "example": "2024-01-15T10:00:00Z",
            "format": "date-time",
            "type": "string"
          },
          "time_spent_ms": {
            "description": "Time spent on step in milliseconds",
            "example": 1800000,
            "type": "number"
          }
        },
        "required": [
          "started_at"
        ],
        "type": "object"
      },
      "StepTrackingCompleteRequest": {
        "properties": {
          "company_id": {
            "description": "Company ID for multi-company tracking",
            "example": "comp_123456",
            "type": "string"
          },
          "fields_modified": {
            "description": "Fields that were modified in this step",
            "example": [
              "company_name",
              "business_purpose"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "step_index": {
            "description": "Step index (0-17)",
            "example": 3,
            "maximum": 17,
            "minimum": 0,
            "type": "number"
          }
        },
        "required": [
          "step_index"
        ],
        "type": "object"
      },
      "StepTrackingStartRequest": {
        "properties": {
          "company_id": {
            "description": "Company ID for multi-company tracking",
            "example": "comp_123456",
            "type": "string"
          },
          "step_index": {
            "description": "Step index (0-17)",
            "example": 3,
            "maximum": 17,
            "minimum": 0,
            "type": "number"
          }
        },
        "required": [
          "step_index"
        ],
        "type": "object"
      },
      "StepsMetadataResponse": {
        "properties": {
          "data": {
            "items": {
              "$ref": "#/components/schemas/StepMetadata"
            },
            "type": "array"
          },
          "success": {
            "example": true,
            "type": "boolean"
          },
          "timestamp": {
            "example": "2024-01-15T10:30:00Z",
            "format": "date-time",
            "type": "string"
          }
        },
        "required": [
          "success",
          "data",
          "timestamp"
        ],
        "type": "object"
      },
      "StoreSessionRequest": {
        "properties": {
          "etax_user_id": {
            "description": "ETax user ID for session",
            "example": "user123",
            "type": "string"
          },
          "expires_in": {
            "default": 3600,
            "description": "Session expiration time in seconds",
            "example": 3600,
            "type": "integer"
          },
          "session_token": {
            "description": "Session token from ETax authentication",
            "example": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
            "type": "string"
          }
        },
        "required": [
          "etax_user_id",
          "session_token"
        ],
        "type": "object"
      },
      "StreamEvent": {
        "properties": {
          "data": {
            "allOf": [
              {
                "$ref": "#/components/schemas/LogEntry"
              }
            ],
            "description": "Log entry data (only for log events)",
            "nullable": true
          },
          "timestamp": {
            "description": "Event timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "type": {
            "description": "Event type",
            "enum": [
              "connected",
              "heartbeat",
              "log"
            ],
            "example": "log",
            "type": "string"
          }
        },
        "required": [
          "type",
          "timestamp"
        ],
        "type": "object"
      },
      "SubmissionMethod": {
        "description": "Method of submission for statutory tasks",
        "enum": [
          "E_TAX",
          "EL_TAX",
          "MAIL",
          "IN_PERSON",
          "HAND_DELIVERY",
          "ONLINE_PORTAL"
        ],
        "type": "string",
        "x-enum-descriptions": {
          "EL_TAX": "eLTAX (地方税)",
          "E_TAX": "e-Tax (国税)",
          "HAND_DELIVERY": "手渡し",
          "IN_PERSON": "窓口",
          "MAIL": "郵送",
          "ONLINE_PORTAL": "オンラインポータル"
        }
      },
      "SuggestGroupingsRequest": {
        "properties": {
          "session_id": {
            "format": "uuid",
            "type": "string"
          }
        },
        "required": [
          "session_id"
        ],
        "type": "object"
      },
      "SuggestRulesApiResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/SuggestRulesResponse"
          },
          "message": {
            "example": "Rules suggested successfully",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "SuggestRulesRequest": {
        "properties": {
          "existingRules": {
            "description": "Existing automation rules",
            "items": {
              "$ref": "#/components/schemas/ExistingRule"
            },
            "type": "array"
          },
          "transactionHistory": {
            "description": "Historical transaction data",
            "items": {
              "$ref": "#/components/schemas/TransactionHistoryItem"
            },
            "type": "array"
          }
        },
        "required": [
          "transactionHistory"
        ],
        "type": "object"
      },
      "SuggestRulesResponse": {
        "properties": {
          "analysisNotes": {
            "description": "Analysis notes and recommendations",
            "example": [
              "月次の定期取引が多く見られます",
              "手動確認が必要な高額取引があります"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "suggestedRules": {
            "description": "List of suggested automation rules",
            "items": {
              "$ref": "#/components/schemas/SuggestedRule"
            },
            "type": "array"
          }
        },
        "required": [
          "suggestedRules",
          "analysisNotes"
        ],
        "type": "object"
      },
      "SuggestedAccount": {
        "properties": {
          "code": {
            "description": "Account code",
            "example": "6101",
            "type": "string"
          },
          "confidence": {
            "description": "Confidence score (0-1)",
            "example": 0.85,
            "format": "double",
            "maximum": 1,
            "minimum": 0,
            "type": "number"
          },
          "name": {
            "description": "Account name",
            "example": "消耗品費",
            "type": "string"
          },
          "subAccount": {
            "description": "Sub-account classification",
            "example": "オフィス用品",
            "type": "string"
          }
        },
        "required": [
          "code",
          "name",
          "confidence"
        ],
        "type": "object"
      },
      "SuggestedAction": {
        "description": "Suggested action for document match",
        "enum": [
          "LINK_AND_RECONCILE",
          "LINK_ONLY",
          "NEEDS_REVIEW"
        ],
        "example": "LINK_AND_RECONCILE",
        "type": "string"
      },
      "SuggestedRule": {
        "properties": {
          "actions": {
            "$ref": "#/components/schemas/SuggestedRuleActions"
          },
          "conditions": {
            "$ref": "#/components/schemas/SuggestedRuleConditions"
          },
          "confidence": {
            "description": "Rule confidence score",
            "example": 0.88,
            "format": "double",
            "maximum": 1,
            "minimum": 0,
            "type": "number"
          },
          "name": {
            "description": "Suggested rule name",
            "example": "Amazon購入自動分類ルール",
            "type": "string"
          },
          "priority": {
            "description": "Rule priority (1=highest)",
            "example": 1,
            "type": "integer"
          },
          "reasoning": {
            "description": "Reasoning for rule suggestion",
            "example": "Amazonからの購入が頻繁で、金額帯も一定しているため自動化に適しています",
            "type": "string"
          }
        },
        "required": [
          "name",
          "conditions",
          "actions",
          "confidence",
          "reasoning",
          "priority"
        ],
        "type": "object"
      },
      "SuggestedRuleActions": {
        "properties": {
          "accountCode": {
            "description": "Suggested account code",
            "example": "6101",
            "type": "string"
          },
          "autoJournalize": {
            "description": "Enable automatic journal entry",
            "example": false,
            "type": "boolean"
          },
          "autoReconcile": {
            "description": "Enable automatic reconciliation",
            "example": true,
            "type": "boolean"
          },
          "category": {
            "description": "Suggested category",
            "example": "消耗品費",
            "type": "string"
          },
          "subAccount": {
            "description": "Suggested sub-account",
            "example": "オフィス用品",
            "type": "string"
          },
          "taxCategory": {
            "description": "Suggested tax category",
            "example": "課税仕入",
            "type": "string"
          }
        },
        "required": [
          "category",
          "accountCode",
          "taxCategory",
          "autoReconcile",
          "autoJournalize"
        ],
        "type": "object"
      },
      "SuggestedRuleConditions": {
        "properties": {
          "amountRange": {
            "$ref": "#/components/schemas/AmountRange"
          },
          "descriptionContains": {
            "description": "Description keywords",
            "example": [
              "Amazon"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "descriptionPattern": {
            "description": "Description pattern (regex)",
            "example": "Amazon.*",
            "type": "string"
          },
          "frequency": {
            "$ref": "#/components/schemas/RuleFrequency"
          },
          "transactionType": {
            "$ref": "#/components/schemas/TransactionType"
          }
        },
        "type": "object"
      },
      "SuggestionContext": {
        "properties": {
          "businessDescription": {
            "description": "Business description for company name suggestions",
            "example": "Webアプリケーション開発",
            "type": "string"
          },
          "existingValues": {
            "description": "Current user inputs to avoid duplicate suggestions",
            "example": [
              "ソフトウェア開発",
              "システム設計"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "industry": {
            "description": "Industry for business purpose suggestions",
            "example": "IT",
            "type": "string"
          },
          "licenseType": {
            "description": "Type of license if applicable",
            "example": "古物商許可",
            "type": "string"
          },
          "monthlyExpenses": {
            "description": "Expected monthly expenses for capital recommendations",
            "example": 500000,
            "type": "number"
          },
          "requiresLicense": {
            "description": "Whether business requires special licenses",
            "example": false,
            "type": "boolean"
          },
          "willHireEmployees": {
            "description": "Whether planning to hire employees",
            "example": true,
            "type": "boolean"
          }
        },
        "type": "object"
      },
      "SuggestionSource": {
        "description": "Source of the category suggestion",
        "enum": [
          "ai",
          "vendor_rule",
          "keyword_rule",
          "user_rule",
          "user_history",
          "default"
        ],
        "type": "string"
      },
      "SuggestionType": {
        "description": "Type of field-specific suggestion",
        "enum": [
          "business_purpose",
          "company_name",
          "capital",
          "general"
        ],
        "example": "business_purpose",
        "type": "string"
      },
      "SupabaseConfig": {
        "properties": {
          "description": {
            "description": "Feature description",
            "example": "Database-level security policies",
            "type": "string"
          },
          "envVar": {
            "description": "Related environment variable",
            "example": "SUPABASE_URL",
            "nullable": true,
            "type": "string"
          },
          "feature": {
            "description": "Supabase feature name",
            "example": "Row Level Security",
            "type": "string"
          }
        },
        "required": [
          "feature",
          "description"
        ],
        "type": "object"
      },
      "SupabaseConfigResponse": {
        "properties": {
          "data": {
            "description": "Supabase configuration",
            "items": {
              "$ref": "#/components/schemas/SupabaseConfig"
            },
            "type": "array"
          },
          "message": {
            "example": "Supabase configuration retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "SupportedGenerationTypesResponse": {
        "properties": {
          "data": {
            "items": {
              "properties": {
                "name": {
                  "example": "請求書",
                  "type": "string"
                },
                "type": {
                  "example": "sales_invoice",
                  "type": "string"
                }
              },
              "required": [
                "type",
                "name"
              ],
              "type": "object"
            },
            "type": "array"
          },
          "message": {
            "example": "Supported generation types retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "SyncExpenseRequest": {
        "properties": {
          "claims_document_id": {
            "description": "Claims document ID containing the expense",
            "example": "456e7890-f12a-34b5-c678-901234567890",
            "format": "uuid",
            "type": "string"
          },
          "expense_id": {
            "description": "Expense ID to sync across linked documents",
            "example": "exp12345-6789-abcd-efgh-ijklmnopqrst",
            "format": "uuid",
            "type": "string"
          }
        },
        "required": [
          "claims_document_id",
          "expense_id"
        ],
        "type": "object"
      },
      "SyncResult": {
        "properties": {
          "connectionId": {
            "format": "uuid",
            "type": "string"
          },
          "dateFrom": {
            "example": "2025-11-01",
            "format": "date",
            "type": "string"
          },
          "dateTo": {
            "example": "2026-02-11",
            "format": "date",
            "type": "string"
          },
          "durationMs": {
            "example": 1834,
            "type": "integer"
          },
          "syncLogId": {
            "format": "uuid",
            "type": "string"
          },
          "transactionsDuplicated": {
            "example": 35,
            "type": "integer"
          },
          "transactionsFetched": {
            "example": 47,
            "type": "integer"
          },
          "transactionsInserted": {
            "example": 12,
            "type": "integer"
          }
        },
        "type": "object"
      },
      "SystemMetrics": {
        "properties": {
          "environment": {
            "example": "production",
            "type": "string"
          },
          "memoryUsage": {
            "properties": {
              "external": {
                "description": "External memory (MB)",
                "example": 12,
                "type": "number"
              },
              "heapTotal": {
                "description": "Total heap memory (MB)",
                "example": 256,
                "type": "number"
              },
              "heapUsed": {
                "description": "Heap memory used (MB)",
                "example": 128,
                "type": "number"
              },
              "percentUsed": {
                "description": "Heap usage percentage",
                "example": 50,
                "type": "number"
              },
              "rss": {
                "description": "Resident Set Size (MB)",
                "example": 320,
                "type": "number"
              }
            },
            "type": "object"
          },
          "nodeVersion": {
            "example": "v20.10.0",
            "type": "string"
          },
          "uptime": {
            "description": "Process uptime in seconds",
            "example": 86400,
            "type": "number"
          }
        },
        "type": "object"
      },
      "SystemStats": {
        "properties": {
          "connectedClients": {
            "description": "Number of connected SSE clients",
            "example": 12,
            "type": "integer"
          },
          "queueStatus": {
            "$ref": "#/components/schemas/QueueStatus"
          },
          "systemHealth": {
            "properties": {
              "cpuUsage": {
                "example": 45.7,
                "type": "number"
              },
              "memoryUsage": {
                "example": 85.2,
                "type": "number"
              },
              "uptime": {
                "example": 86400,
                "type": "number"
              }
            },
            "type": "object"
          }
        },
        "required": [
          "queueStatus",
          "connectedClients"
        ],
        "type": "object"
      },
      "SystemStatsResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/SystemStats"
          },
          "message": {
            "example": "System statistics retrieved successfully",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "TargetSoftware": {
        "description": "Target accounting software for format-specific export",
        "enum": [
          "generic",
          "yayoi",
          "freee",
          "pca",
          "jdl",
          "tkc",
          "kanjo_bugyo",
          "zaimu_ouen",
          "mjs"
        ],
        "example": "yayoi",
        "type": "string"
      },
      "TaskAction": {
        "description": "An action within a statutory task",
        "properties": {
          "actionLabel": {
            "description": "Japanese label for the action",
            "example": "提出",
            "type": "string"
          },
          "actionType": {
            "$ref": "#/components/schemas/TaskActionType"
          },
          "condition": {
            "$ref": "#/components/schemas/TaskCondition"
          },
          "displayOrder": {
            "description": "Display order for UI",
            "example": 1,
            "type": "integer"
          },
          "id": {
            "description": "Action unique identifier",
            "format": "uuid",
            "type": "string"
          },
          "isDone": {
            "description": "Whether this action is completed",
            "example": false,
            "type": "boolean"
          },
          "isRequired": {
            "description": "Whether this action is always required",
            "example": true,
            "type": "boolean"
          },
          "method": {
            "$ref": "#/components/schemas/TaskMethod"
          },
          "recipient": {
            "$ref": "#/components/schemas/TaskRecipient"
          }
        },
        "required": [
          "id",
          "actionType",
          "actionLabel",
          "recipient",
          "isRequired",
          "isDone",
          "displayOrder"
        ],
        "type": "object"
      },
      "TaskActionType": {
        "description": "Type of action for statutory tasks",
        "enum": [
          "SUBMIT",
          "DISTRIBUTE",
          "FILE",
          "REPORT",
          "PAY"
        ],
        "type": "string",
        "x-enum-descriptions": {
          "DISTRIBUTE": "交付 (to employees)",
          "FILE": "申告",
          "PAY": "納付",
          "REPORT": "届出",
          "SUBMIT": "提出 (to government)"
        }
      },
      "TaskCondition": {
        "description": "Condition for conditional actions",
        "properties": {
          "isMet": {
            "description": "Whether the condition is currently met",
            "example": false,
            "type": "boolean"
          },
          "key": {
            "description": "Condition identifier",
            "example": "HIGH_EARNER",
            "type": "string"
          },
          "label": {
            "description": "Japanese description of the condition",
            "example": "役員年収 >¥150万 または 従業員年収 >¥500万",
            "type": "string"
          }
        },
        "required": [
          "key",
          "label",
          "isMet"
        ],
        "type": "object"
      },
      "TaskMethod": {
        "properties": {
          "label": {
            "description": "Label for the submission method",
            "example": "e-Tax",
            "type": "string"
          },
          "type": {
            "$ref": "#/components/schemas/SubmissionMethod"
          }
        },
        "required": [
          "type",
          "label"
        ],
        "type": "object"
      },
      "TaskRecipient": {
        "properties": {
          "label": {
            "description": "Japanese label for the recipient",
            "example": "所轄税務署",
            "type": "string"
          },
          "type": {
            "$ref": "#/components/schemas/TaskRecipientType"
          }
        },
        "required": [
          "type",
          "label"
        ],
        "type": "object"
      },
      "TaskRecipientType": {
        "description": "Type of recipient for statutory task actions",
        "enum": [
          "TAX_OFFICE",
          "MUNICIPALITY",
          "EMPLOYEE",
          "PENSION_OFFICE",
          "LABOR_BUREAU",
          "SELF"
        ],
        "type": "string",
        "x-enum-descriptions": {
          "EMPLOYEE": "従業員",
          "LABOR_BUREAU": "労働基準監督署",
          "MUNICIPALITY": "市区町村",
          "PENSION_OFFICE": "年金事務所",
          "SELF": "自分",
          "TAX_OFFICE": "所轄税務署"
        }
      },
      "TaxAuditAnalyzeRequest": {
        "properties": {
          "companyId": {
            "description": "Company ID for analysis",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "documentTypes": {
            "description": "Types of documents to include in analysis",
            "example": [
              "invoices",
              "receipts",
              "contracts"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "endDate": {
            "description": "Analysis period end date (optional)",
            "example": "2024-12-31",
            "format": "date",
            "type": "string"
          },
          "includeCashBook": {
            "description": "Include cash book in analysis",
            "example": false,
            "type": "boolean"
          },
          "includeExpenseReports": {
            "description": "Include expense reports in analysis",
            "example": true,
            "type": "boolean"
          },
          "includeGeneralLedger": {
            "description": "Include general ledger in analysis",
            "example": true,
            "type": "boolean"
          },
          "includeJournal": {
            "description": "Include journal entries in analysis",
            "example": true,
            "type": "boolean"
          },
          "startDate": {
            "description": "Analysis period start date (optional)",
            "example": "2024-01-01",
            "format": "date",
            "type": "string"
          }
        },
        "required": [
          "companyId"
        ],
        "type": "object"
      },
      "TaxAuditIssue": {
        "properties": {
          "affectedAmount": {
            "description": "Financial amount affected by this issue",
            "example": 25000,
            "format": "decimal",
            "type": "number"
          },
          "category": {
            "description": "Issue category",
            "example": "消費税計算",
            "type": "string"
          },
          "description": {
            "description": "Detailed issue description",
            "example": "軽減税率対象商品に標準税率が適用されています",
            "type": "string"
          },
          "id": {
            "description": "Unique issue identifier",
            "example": "issue_001",
            "type": "string"
          },
          "recommendation": {
            "description": "Recommended action to resolve the issue",
            "example": "該当取引の消費税率を8%に修正してください",
            "type": "string"
          },
          "severity": {
            "$ref": "#/components/schemas/IssueSeverity"
          },
          "taxCodeReference": {
            "description": "Reference to relevant tax code or regulation",
            "example": "消費税法第29条",
            "type": "string"
          },
          "title": {
            "description": "Issue title",
            "example": "消費税率の適用誤り",
            "type": "string"
          }
        },
        "required": [
          "id",
          "severity",
          "category",
          "title",
          "description",
          "recommendation"
        ],
        "type": "object"
      },
      "TaxAuditJobResponse": {
        "properties": {
          "completedAt": {
            "description": "Job completion timestamp",
            "example": "2024-03-15T14:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "createdAt": {
            "description": "Job creation timestamp",
            "example": "2024-03-15T14:00:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "error": {
            "description": "Error message if job failed",
            "example": "データの取得に失敗しました",
            "type": "string"
          },
          "jobId": {
            "description": "Unique job identifier",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "progress": {
            "description": "Job completion progress percentage",
            "example": 65,
            "format": "double",
            "maximum": 100,
            "minimum": 0,
            "type": "number"
          },
          "result": {
            "$ref": "#/components/schemas/TaxAuditResult"
          },
          "status": {
            "$ref": "#/components/schemas/JobStatus"
          }
        },
        "required": [
          "jobId",
          "status",
          "createdAt"
        ],
        "type": "object"
      },
      "TaxAuditRecommendation": {
        "properties": {
          "action": {
            "description": "Recommended action",
            "example": "仕入税額控除の要件確認を強化する",
            "type": "string"
          },
          "expectedBenefit": {
            "description": "Expected benefit from implementing the recommendation",
            "example": "コンプライアンスリスクの軽減と税務調査対応の改善",
            "type": "string"
          },
          "priority": {
            "$ref": "#/components/schemas/Priority"
          }
        },
        "required": [
          "priority",
          "action",
          "expectedBenefit"
        ],
        "type": "object"
      },
      "TaxAuditResult": {
        "properties": {
          "analysisDate": {
            "description": "Date and time of analysis completion",
            "example": "2024-03-15T14:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "complianceScore": {
            "description": "Overall compliance score (0-100)",
            "example": 78.5,
            "format": "double",
            "maximum": 100,
            "minimum": 0,
            "type": "number"
          },
          "issues": {
            "description": "List of identified issues",
            "items": {
              "$ref": "#/components/schemas/TaxAuditIssue"
            },
            "type": "array"
          },
          "recommendations": {
            "description": "List of improvement recommendations",
            "items": {
              "$ref": "#/components/schemas/TaxAuditRecommendation"
            },
            "type": "array"
          },
          "summary": {
            "$ref": "#/components/schemas/TaxAuditSummary"
          }
        },
        "required": [
          "summary",
          "issues",
          "recommendations",
          "complianceScore",
          "analysisDate"
        ],
        "type": "object"
      },
      "TaxAuditStartResponse": {
        "properties": {
          "data": {
            "properties": {
              "jobId": {
                "example": "123e4567-e89b-12d3-a456-426614174000",
                "format": "uuid",
                "type": "string"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Tax audit analysis started",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "TaxAuditStatusResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/TaxAuditJobResponse"
          },
          "message": {
            "example": "Job status retrieved",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "TaxAuditSummary": {
        "properties": {
          "criticalIssues": {
            "description": "Number of critical issues",
            "example": 2,
            "type": "integer"
          },
          "infoIssues": {
            "description": "Number of informational issues",
            "example": 3,
            "type": "integer"
          },
          "overallRisk": {
            "$ref": "#/components/schemas/RiskLevel"
          },
          "totalIssuesFound": {
            "description": "Total number of issues identified",
            "example": 12,
            "type": "integer"
          },
          "warningIssues": {
            "description": "Number of warning issues",
            "example": 7,
            "type": "integer"
          }
        },
        "required": [
          "overallRisk",
          "totalIssuesFound"
        ],
        "type": "object"
      },
      "TaxBracket": {
        "properties": {
          "deduction": {
            "description": "Tax deduction amount for this bracket",
            "example": "0円",
            "type": "string"
          },
          "range": {
            "description": "Income range for this tax bracket",
            "example": "1,950,000円以下",
            "type": "string"
          },
          "rate": {
            "description": "Tax rate for this bracket",
            "example": "5%",
            "type": "string"
          }
        },
        "required": [
          "range",
          "rate",
          "deduction"
        ],
        "type": "object"
      },
      "TaxBracketReferenceResponse": {
        "properties": {
          "data": {
            "properties": {
              "brackets": {
                "items": {
                  "$ref": "#/components/schemas/TaxBracket"
                },
                "type": "array"
              },
              "formula": {
                "example": "税額 = 課税所得金額 × 税率 - 控除額",
                "type": "string"
              },
              "note": {
                "example": "復興特別所得税（2.1%）は別途加算",
                "type": "string"
              }
            },
            "type": "object"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "TaxBreakdown": {
        "description": "Detailed tax breakdown for method comparison",
        "properties": {
          "exempt_sales": {
            "description": "Exempt sales amount",
            "example": 0,
            "type": "number"
          },
          "input_tax_credit": {
            "description": "Input tax credit amount",
            "example": 400000,
            "type": "number"
          },
          "reduced_rate_sales": {
            "description": "Reduced rate (8%) sales amount",
            "example": 0,
            "type": "number"
          },
          "reduced_rate_tax": {
            "description": "Reduced rate output tax",
            "example": 0,
            "type": "number"
          },
          "standard_rate_sales": {
            "description": "Standard rate (10%) sales amount",
            "example": 10000000,
            "type": "number"
          },
          "standard_rate_tax": {
            "description": "Standard rate output tax",
            "example": 1000000,
            "type": "number"
          },
          "total_input_tax": {
            "description": "Total input tax (仮払消費税)",
            "example": 400000,
            "type": "number"
          },
          "total_output_tax": {
            "description": "Total output tax (仮受消費税)",
            "example": 1000000,
            "type": "number"
          },
          "total_sales": {
            "description": "Total sales amount",
            "example": 10000000,
            "type": "number"
          }
        },
        "type": "object"
      },
      "TaxCalculationMethod": {
        "description": "Consumption tax calculation method",
        "enum": [
          "general",
          "simplified",
          "special_20"
        ],
        "example": "general",
        "type": "string"
      },
      "TaxComplianceActionResponse": {
        "properties": {
          "data": {
            "properties": {
              "action": {
                "example": "period_closed",
                "type": "string"
              },
              "success": {
                "example": true,
                "type": "boolean"
              },
              "timestamp": {
                "format": "date-time",
                "type": "string"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Action completed successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "TaxComplianceInitResponse": {
        "description": "Composite response combining journal summary and bank statements for tax compliance page",
        "properties": {
          "data": {
            "properties": {
              "bankStatements": {
                "description": "Paginated bank statements (銀行明細)",
                "nullable": true,
                "properties": {
                  "items": {
                    "description": "Bank statement records",
                    "items": {
                      "properties": {
                        "balance": {
                          "example": 1500000,
                          "type": "integer"
                        },
                        "deposit_amount": {
                          "example": 100000,
                          "type": "integer"
                        },
                        "description": {
                          "example": "振込 カブシキガイシャABC",
                          "type": "string"
                        },
                        "id": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "transaction_date": {
                          "example": 20250115,
                          "type": "integer"
                        },
                        "withdrawal_amount": {
                          "example": 0,
                          "type": "integer"
                        }
                      },
                      "type": "object"
                    },
                    "type": "array"
                  },
                  "pagination": {
                    "properties": {
                      "currentPage": {
                        "example": 1,
                        "type": "integer"
                      },
                      "hasNext": {
                        "example": true,
                        "type": "boolean"
                      },
                      "hasPrevious": {
                        "example": false,
                        "type": "boolean"
                      },
                      "pageSize": {
                        "example": 20,
                        "type": "integer"
                      },
                      "totalItems": {
                        "example": 150,
                        "type": "integer"
                      },
                      "totalPages": {
                        "example": 8,
                        "type": "integer"
                      }
                    },
                    "type": "object"
                  }
                },
                "type": "object"
              },
              "journalSummaryByAccount": {
                "description": "Journal entries summary grouped by account (総勘定元帳)",
                "nullable": true,
                "properties": {
                  "accountSummaries": {
                    "description": "Array of account-level summaries",
                    "items": {
                      "properties": {
                        "account": {
                          "properties": {
                            "code": {
                              "example": "101",
                              "type": "string"
                            },
                            "id": {
                              "format": "uuid",
                              "type": "string"
                            },
                            "name": {
                              "example": "現金",
                              "type": "string"
                            },
                            "normalSide": {
                              "enum": [
                                "debit",
                                "credit"
                              ],
                              "type": "string"
                            },
                            "type": {
                              "example": "asset",
                              "type": "string"
                            }
                          },
                          "type": "object"
                        },
                        "creditTotal": {
                          "example": 300000,
                          "type": "number"
                        },
                        "debitTotal": {
                          "example": 500000,
                          "type": "number"
                        },
                        "netAmount": {
                          "example": 200000,
                          "type": "number"
                        },
                        "transactionCount": {
                          "example": 15,
                          "type": "integer"
                        }
                      },
                      "type": "object"
                    },
                    "type": "array"
                  },
                  "balanceDifference": {
                    "example": 0,
                    "type": "number"
                  },
                  "grandTotalCredit": {
                    "example": 5000000,
                    "type": "number"
                  },
                  "grandTotalDebit": {
                    "example": 5000000,
                    "type": "number"
                  },
                  "isBalanced": {
                    "example": true,
                    "type": "boolean"
                  },
                  "totalAccounts": {
                    "example": 25,
                    "type": "integer"
                  }
                },
                "type": "object"
              }
            },
            "type": "object"
          },
          "meta": {
            "description": "Response metadata",
            "properties": {
              "cached": {
                "description": "Whether response was served from memory cache",
                "type": "boolean"
              },
              "durationMs": {
                "description": "Total query time in milliseconds",
                "example": 450,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "type": "object"
      },
      "TaxEligibility": {
        "description": "Eligibility status for simplified and special methods",
        "properties": {
          "reasons": {
            "example": [
              "基準期間（2023年）の課税売上高が5,000万円以下のため、簡易課税を選択できます",
              "2割特例は令和8年9月30日までの経過措置として利用可能です"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "simplified_eligible": {
            "description": "簡易課税を選択可能か",
            "example": true,
            "type": "boolean"
          },
          "special_20_eligible": {
            "description": "2割特例を選択可能か",
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "simplified_eligible",
          "special_20_eligible",
          "reasons"
        ],
        "type": "object"
      },
      "TaxForecastInput": {
        "properties": {
          "consumptionTaxStatus": {
            "default": "taxable",
            "enum": [
              "taxable",
              "simplified",
              "exempt"
            ],
            "type": "string"
          },
          "employeeCount": {
            "example": 0,
            "type": "integer"
          },
          "estimatedAnnualExpenses": {
            "description": "Integer JPY",
            "example": 6000000,
            "type": "integer"
          },
          "estimatedAnnualRevenue": {
            "description": "Integer JPY",
            "example": 10000000,
            "type": "integer"
          },
          "fiscalPeriodEnd": {
            "example": "2026-03-31",
            "format": "date",
            "type": "string"
          },
          "fiscalPeriodStart": {
            "example": "2025-04-01",
            "format": "date",
            "type": "string"
          },
          "officerMonthlyCompensation": {
            "description": "Integer JPY",
            "example": 500000,
            "type": "integer"
          },
          "priorPeriodMonths": {
            "description": "前事業年度の月数 (short first year < 12; default 12) — 予定申告 = 前期法人税 ÷ 月数 × 6",
            "example": 9,
            "maximum": 12,
            "minimum": 1,
            "type": "integer"
          },
          "priorYearCorporateTaxYen": {
            "description": "前期法人税額 (Integer JPY)",
            "example": 250000,
            "type": "integer"
          }
        },
        "required": [
          "fiscalPeriodStart",
          "fiscalPeriodEnd"
        ],
        "type": "object"
      },
      "TaxForecastResult": {
        "properties": {
          "annualConsumptionTax": {
            "type": "integer"
          },
          "annualCorporateTax": {
            "type": "integer"
          },
          "annualSocialInsurance": {
            "type": "integer"
          },
          "annualWithholding": {
            "type": "integer"
          },
          "engineVersion": {
            "type": "string"
          },
          "interimComparison": {
            "type": "object"
          },
          "monthlyObligations": {
            "items": {
              "type": "object"
            },
            "type": "array"
          },
          "recommendedMonthlySweep": {
            "type": "integer"
          }
        },
        "type": "object"
      },
      "TaxJournalInitData": {
        "description": "Only the requested sources are present. Without `include` the payload is exactly what it has\nalways been (unsyncDocuments, signatures, journalEntries, journalSummary, accountSummary, plus healthCheck\nwhen `include_health_check=true`). Every source is read independently: a failed read is `null` (or its\ndocumented empty value) and never fails the call.",
        "properties": {
          "accountSummary": {
            "additionalProperties": true,
            "description": "Per-account breakdown (debit/credit totals, transaction counts).",
            "nullable": true,
            "type": "object"
          },
          "flatJournalPage": {
            "description": "Opt-in (`include=flat_journal_page`, v5.20+). EXACTLY the page `GET /api/journal-entries`\nreturns for this call's `start_date`/`end_date`/`status` with `page=1`, `page_size=500`,\n`include_document_summary=true` and `include_evidence=true` — same service function, same account scope.\n\n**Seeding contract:** `items` is that endpoint's `data` array and `pagination` is its top-level\n`pagination` (canonical keys). Seed the list query's first page from this object ONLY when the list's own\nrange and status equal the ones sent here and no account-code filter is active; otherwise ignore it and let\nthe list fetch. `null` when the read failed — always fall back to the request.\n\nThis source is never served from (or written to) the endpoint's 120 s in-process cache, so a seeded page can\nnever show pre-edit rows.",
            "nullable": true,
            "properties": {
              "items": {
                "items": {
                  "additionalProperties": true,
                  "type": "object"
                },
                "type": "array"
              },
              "pagination": {
                "$ref": "#/components/schemas/Pagination"
              }
            },
            "type": "object"
          },
          "healthCheck": {
            "additionalProperties": true,
            "description": "Data-integrity status. Present only with `include_health_check=true` (or `include=health_check`) AND a successful read — the heaviest source.",
            "nullable": true,
            "type": "object"
          },
          "journalEntries": {
            "additionalProperties": true,
            "description": "Journal entries grouped by source document (paginated).",
            "nullable": true,
            "properties": {
              "items": {
                "items": {
                  "additionalProperties": true,
                  "type": "object"
                },
                "type": "array"
              },
              "pagination": {
                "allOf": [
                  {
                    "$ref": "#/components/schemas/Pagination"
                  }
                ],
                "nullable": true
              }
            },
            "type": "object"
          },
          "journalSummary": {
            "additionalProperties": true,
            "description": "Aggregate totals: totalEntries, totalDebit, totalCredit, isBalanced.",
            "nullable": true,
            "type": "object"
          },
          "signatures": {
            "description": "The caller's signature records (`[]` when the read failed).",
            "items": {
              "additionalProperties": true,
              "type": "object"
            },
            "nullable": true,
            "type": "array"
          },
          "unsyncDocuments": {
            "additionalProperties": true,
            "description": "Documents that still have no journal entry. The 未同期 counter reads `pagination.totalItems` — the\nauthoritative count, independent of how many items came back. With `include=unsync_count` the rows are NOT\nloaded (page size 1) and `items` is always `[]`; without `include` the first 50 rows are returned as\nbefore. `pagination` is `null` only when the read failed.",
            "nullable": true,
            "properties": {
              "items": {
                "items": {
                  "additionalProperties": true,
                  "type": "object"
                },
                "type": "array"
              },
              "pagination": {
                "allOf": [
                  {
                    "$ref": "#/components/schemas/Pagination"
                  }
                ],
                "nullable": true
              }
            },
            "type": "object"
          }
        },
        "type": "object"
      },
      "TaxJournalInitResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/TaxJournalInitData"
          },
          "meta": {
            "properties": {
              "cached": {
                "description": "True when the payload came from the per-user in-process cache (120 s). Always false when `flat_journal_page` was requested.",
                "type": "boolean"
              },
              "durationMs": {
                "example": 180,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data",
          "meta"
        ],
        "type": "object"
      },
      "TaxMethodDetail": {
        "description": "Detailed calculation result for a single method",
        "properties": {
          "breakdown": {
            "$ref": "#/components/schemas/TaxBreakdown"
          },
          "business_type": {
            "description": "Business type (for simplified)",
            "example": "service",
            "type": "string"
          },
          "deemed_purchase_ratio": {
            "description": "Deemed purchase rate % (for simplified)",
            "example": 50,
            "type": "number"
          },
          "effective_rate": {
            "description": "Effective tax rate",
            "example": 0.06,
            "type": "number"
          },
          "fiscal_year": {
            "example": 2025,
            "type": "integer"
          },
          "method": {
            "enum": [
              "general",
              "simplified",
              "special_20"
            ],
            "example": "general",
            "type": "string"
          },
          "method_label_ja": {
            "description": "Japanese method name",
            "example": "一般課税方式",
            "type": "string"
          },
          "period_end": {
            "example": "2025-12-31",
            "format": "date",
            "type": "string"
          },
          "period_start": {
            "example": "2025-01-01",
            "format": "date",
            "type": "string"
          },
          "tax_due": {
            "description": "Tax due amount (納付税額)",
            "example": 600000,
            "type": "number"
          },
          "tax_refund": {
            "description": "Tax refund if negative",
            "example": 0,
            "type": "number"
          }
        },
        "required": [
          "method",
          "method_label_ja",
          "breakdown",
          "tax_due",
          "effective_rate"
        ],
        "type": "object"
      },
      "TaxPaymentMatch": {
        "properties": {
          "amountYen": {
            "type": "integer"
          },
          "bankLines": {
            "items": {
              "$ref": "#/components/schemas/TaxPaymentMatchBankLine"
            },
            "minItems": 1,
            "type": "array"
          },
          "confidence": {
            "enum": [
              "exact"
            ],
            "type": "string"
          },
          "id": {
            "description": "`${kind}:${targetId}:${bankIds joined by +}` — the same pairing keeps the same id.",
            "example": "office_payment:0b8f2a8e-7a1c-4d2b-9e3f-5a6b7c8d9e0f:9d1e2f3a-4b5c-4d6e-8f70-1a2b3c4d5e6f",
            "type": "string"
          },
          "kind": {
            "description": "deadline_paid: an open deadline row the bank shows fully paid (confirm = 「納付しました」). office_payment: an office_tax_payments row without its bank line (confirm links it).",
            "enum": [
              "deadline_paid",
              "office_payment"
            ],
            "type": "string"
          },
          "paidOn": {
            "description": "The last withdrawal’s date — recorded as 納付日 on confirm.",
            "format": "date",
            "type": "string"
          },
          "target": {
            "properties": {
              "dueDate": {
                "format": "date",
                "type": "string"
              },
              "id": {
                "description": "deadline_objects.id or office_tax_payments.id",
                "format": "uuid",
                "type": "string"
              },
              "officeName": {
                "description": "office_payment only",
                "nullable": true,
                "type": "string"
              },
              "periodLabel": {
                "example": "FY2027 中間",
                "type": "string"
              },
              "ruleKey": {
                "description": "deadline_paid only",
                "nullable": true,
                "type": "string"
              },
              "taxKind": {
                "description": "office_payment only",
                "nullable": true,
                "type": "string"
              },
              "title": {
                "example": "法人住民税（中間）（群馬事業所）",
                "type": "string"
              }
            },
            "required": [
              "id",
              "title",
              "dueDate",
              "periodLabel",
              "ruleKey",
              "officeName",
              "taxKind"
            ],
            "type": "object"
          }
        },
        "required": [
          "id",
          "kind",
          "confidence",
          "target",
          "paidOn",
          "amountYen",
          "bankLines"
        ],
        "type": "object"
      },
      "TaxPaymentMatchBankLine": {
        "properties": {
          "amountYen": {
            "example": 1700,
            "type": "integer"
          },
          "date": {
            "example": "2026-10-15",
            "format": "date",
            "type": "string"
          },
          "description": {
            "example": "PE 地方税共同機構 12345678901",
            "nullable": true,
            "type": "string"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          }
        },
        "required": [
          "id",
          "date",
          "amountYen",
          "description"
        ],
        "type": "object"
      },
      "TaxPaymentMatchIdsRequest": {
        "properties": {
          "ids": {
            "items": {
              "maxLength": 300,
              "type": "string"
            },
            "maxItems": 50,
            "minItems": 1,
            "type": "array"
          }
        },
        "required": [
          "ids"
        ],
        "type": "object"
      },
      "TaxPaymentMatchWriteResult": {
        "properties": {
          "applied": {
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "skipped": {
            "items": {
              "properties": {
                "id": {
                  "type": "string"
                },
                "reason": {
                  "description": "stale: no longer a suggestion (recorded, dismissed or changed); already_linked: the payment or the withdrawal was linked meanwhile; refused: the deadline could not be recorded (e.g. SBC completed it).",
                  "enum": [
                    "stale",
                    "already_linked",
                    "refused"
                  ],
                  "type": "string"
                }
              },
              "required": [
                "id",
                "reason"
              ],
              "type": "object"
            },
            "type": "array"
          }
        },
        "required": [
          "applied",
          "skipped"
        ],
        "type": "object"
      },
      "TaxRate": {
        "description": "Japanese consumption tax rate classification",
        "enum": [
          "standard_10",
          "reduced_8",
          "non_taxable",
          "tax_exempt",
          "outside_scope"
        ],
        "example": "standard_10",
        "type": "string"
      },
      "TaxRateCategory": {
        "description": "Tax rate category for Japanese consumption tax",
        "enum": [
          "standard_10",
          "reduced_8",
          "exempt"
        ],
        "example": "standard_10",
        "type": "string"
      },
      "TaxRateReference": {
        "properties": {
          "description": {
            "description": "Tax rate description",
            "example": "通常の消費税率",
            "type": "string"
          },
          "label": {
            "description": "Tax rate label in Japanese",
            "example": "標準税率",
            "type": "string"
          },
          "rate": {
            "description": "Tax rate percentage",
            "example": 10,
            "type": "number"
          },
          "value": {
            "description": "Tax rate category value",
            "example": "standard_10",
            "type": "string"
          }
        },
        "required": [
          "value",
          "label",
          "rate",
          "description"
        ],
        "type": "object"
      },
      "TaxRateReferenceResponse": {
        "properties": {
          "data": {
            "properties": {
              "examples": {
                "properties": {
                  "exempt": {
                    "example": [
                      "土地の売買",
                      "住宅の賃貸",
                      "保険料"
                    ],
                    "items": {
                      "type": "string"
                    },
                    "type": "array"
                  },
                  "reduced_8": {
                    "example": [
                      "お弁当",
                      "飲料水",
                      "食品原材料"
                    ],
                    "items": {
                      "type": "string"
                    },
                    "type": "array"
                  },
                  "standard_10": {
                    "example": [
                      "コンサルティング費用",
                      "ソフトウェア開発",
                      "事務用品"
                    ],
                    "items": {
                      "type": "string"
                    },
                    "type": "array"
                  }
                },
                "type": "object"
              },
              "taxRateCategories": {
                "items": {
                  "$ref": "#/components/schemas/TaxRateReference"
                },
                "type": "array"
              }
            },
            "type": "object"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "TaxRateSummary": {
        "properties": {
          "purchaseAmount": {
            "description": "Taxable purchase amount excluding tax (課税仕入高・税抜)",
            "example": 3000000,
            "format": "decimal",
            "type": "number"
          },
          "purchaseTax": {
            "description": "Input tax amount (仮払消費税)",
            "example": 300000,
            "format": "decimal",
            "type": "number"
          },
          "rate": {
            "description": "Tax rate percentage",
            "example": 10,
            "type": "number"
          },
          "salesAmount": {
            "description": "Taxable sales amount excluding tax (課税売上高・税抜)",
            "example": 5000000,
            "format": "decimal",
            "type": "number"
          },
          "salesTax": {
            "description": "Output tax amount (仮受消費税)",
            "example": 500000,
            "format": "decimal",
            "type": "number"
          }
        },
        "required": [
          "rate",
          "salesAmount",
          "salesTax",
          "purchaseAmount",
          "purchaseTax"
        ],
        "type": "object"
      },
      "TaxRecommendation": {
        "properties": {
          "bestMethod": {
            "$ref": "#/components/schemas/TaxCalculationMethod"
          },
          "reason": {
            "description": "Detailed explanation for the recommendation",
            "example": "2割特例が最も有利です。インボイス制度の経過措置として、¥110,000の節税となります。",
            "type": "string"
          },
          "savings": {
            "description": "Potential tax savings in JPY",
            "example": 110000,
            "format": "decimal",
            "type": "number"
          }
        },
        "required": [
          "bestMethod",
          "savings",
          "reason"
        ],
        "type": "object"
      },
      "TaxRecommendationDetail": {
        "description": "Recommendation result with reason",
        "properties": {
          "best_method": {
            "enum": [
              "general",
              "simplified",
              "special_20"
            ],
            "example": "simplified",
            "type": "string"
          },
          "reason": {
            "example": "簡易課税方式が最も有利です。みなし仕入率の適用により、¥100,000の節税が可能です。",
            "type": "string"
          },
          "savings_amount": {
            "description": "Potential savings in JPY",
            "example": 100000,
            "type": "number"
          }
        },
        "required": [
          "best_method",
          "savings_amount",
          "reason"
        ],
        "type": "object"
      },
      "TaxSummary": {
        "properties": {
          "subtotal": {
            "description": "Subtotal excluding tax (税抜合計)",
            "example": 500000,
            "format": "decimal",
            "type": "number"
          },
          "taxAmount": {
            "description": "Tax amount (消費税額)",
            "example": 50000,
            "format": "decimal",
            "type": "number"
          },
          "taxRate": {
            "description": "Tax rate percentage",
            "example": 10,
            "type": "number"
          },
          "taxRateCategory": {
            "$ref": "#/components/schemas/TaxRateCategory"
          },
          "total": {
            "description": "Total including tax (税込合計)",
            "example": 550000,
            "format": "decimal",
            "type": "number"
          }
        },
        "required": [
          "taxRateCategory",
          "taxRate",
          "subtotal",
          "taxAmount",
          "total"
        ],
        "type": "object"
      },
      "TaxTableData": {
        "description": "Complete tax table data (税額表データ)",
        "properties": {
          "japaneseYear": {
            "example": "令和7年",
            "type": "string"
          },
          "metadata": {
            "properties": {
              "kouColumns": {
                "example": [
                  "扶養0人",
                  "扶養1人",
                  "扶養2人",
                  "扶養3人",
                  "扶養4人",
                  "扶養5人",
                  "扶養6人",
                  "扶養7人以上"
                ],
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              "lastUpdated": {
                "format": "date-time",
                "type": "string"
              },
              "ntaSourceUrl": {
                "nullable": true,
                "type": "string"
              },
              "rowCount": {
                "example": 42,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "rows": {
            "items": {
              "$ref": "#/components/schemas/TaxTableRow"
            },
            "type": "array"
          },
          "tableType": {
            "example": "monthly",
            "type": "string"
          },
          "year": {
            "example": 2025,
            "type": "integer"
          }
        },
        "type": "object"
      },
      "TaxTableRow": {
        "description": "Single row from the NTA 月額表 (税額表1行, 以上 salaryFrom / 未満 salaryTo). Above the table (740,000円以上) a row is a formula band: kou is the 税額 at salaryFrom plus kouExcessRate of the excess; 乙 is otsuAmount plus otsuExcessRate of the amount over otsuExcessFrom.",
        "properties": {
          "kou": {
            "description": "甲欄税額 (扶養0-7人)",
            "example": [
              7930,
              6320,
              4700,
              3080,
              1470,
              0,
              0,
              0
            ],
            "items": {
              "type": "integer"
            },
            "type": "array"
          },
          "kouExcessRate": {
            "description": "甲欄 formula band: rate of the amount over salaryFrom",
            "example": 0.2042,
            "nullable": true,
            "type": "number"
          },
          "otsuAmount": {
            "description": "乙欄: printed amount, or the base of a formula band",
            "example": 53600,
            "nullable": true,
            "type": "integer"
          },
          "otsuExcessFrom": {
            "description": "乙欄 formula band: threshold the rate applies above",
            "example": 740000,
            "nullable": true,
            "type": "integer"
          },
          "otsuExcessRate": {
            "description": "乙欄 formula band: rate of the amount over otsuExcessFrom",
            "example": 0.4084,
            "nullable": true,
            "type": "number"
          },
          "otsuRate": {
            "description": "乙欄: rate of the whole amount (below the first bracket)",
            "example": 0.03063,
            "nullable": true,
            "type": "number"
          },
          "salaryFrom": {
            "description": "Salary range start (以上)",
            "example": 299000,
            "type": "integer"
          },
          "salaryTo": {
            "description": "Salary range end (未満); null on the top band",
            "example": 302000,
            "nullable": true,
            "type": "integer"
          }
        },
        "type": "object"
      },
      "TaxTableVersion": {
        "description": "Tax table version information (税額表バージョン情報)",
        "properties": {
          "effectiveFrom": {
            "example": "2025-01-01",
            "type": "string"
          },
          "effectiveUntil": {
            "example": "2025-12-31",
            "nullable": true,
            "type": "string"
          },
          "isLatest": {
            "example": true,
            "type": "boolean"
          },
          "japaneseYear": {
            "example": "令和7年",
            "type": "string"
          },
          "lastUpdated": {
            "format": "date-time",
            "type": "string"
          },
          "notes": {
            "nullable": true,
            "type": "string"
          },
          "ntaSourceUrl": {
            "example": "https://www.nta.go.jp/...",
            "nullable": true,
            "type": "string"
          },
          "tableType": {
            "example": "monthly",
            "type": "string"
          },
          "year": {
            "example": 2025,
            "type": "integer"
          }
        },
        "type": "object"
      },
      "TaxTreatment": {
        "properties": {
          "description": {
            "description": "Detailed description of tax treatment",
            "example": "中小企業者等の少額減価償却資産の特例により、取得価額の全額を損金算入可能",
            "type": "string"
          },
          "immediateDeduction": {
            "description": "Whether immediate deduction is possible",
            "example": true,
            "type": "boolean"
          },
          "type": {
            "$ref": "#/components/schemas/TaxTreatmentType"
          }
        },
        "required": [
          "type",
          "description",
          "immediateDeduction"
        ],
        "type": "object"
      },
      "TaxTreatmentType": {
        "description": "Japanese tax treatment type",
        "enum": [
          "少額減価償却資産",
          "中小企業者等の特例"
        ],
        "example": "中小企業者等の特例",
        "type": "string"
      },
      "TaxableAsset": {
        "description": "Fixed asset subject to 償却資産申告",
        "properties": {
          "acquisitionCost": {
            "example": 350000,
            "type": "number"
          },
          "acquisitionDate": {
            "example": 20250615,
            "type": "integer"
          },
          "bankStatement": {
            "nullable": true,
            "properties": {
              "description": {
                "nullable": true,
                "type": "string"
              },
              "id": {
                "format": "uuid",
                "type": "string"
              }
            },
            "type": "object"
          },
          "classification": {
            "example": 2,
            "type": "integer"
          },
          "classificationName": {
            "example": "建物附属設備",
            "type": "string"
          },
          "closingBookValue": {
            "example": 280000,
            "type": "number"
          },
          "depreciationMethod": {
            "example": 1,
            "type": "integer"
          },
          "document": {
            "nullable": true,
            "properties": {
              "documentName": {
                "nullable": true,
                "type": "string"
              },
              "id": {
                "format": "uuid",
                "type": "string"
              }
            },
            "type": "object"
          },
          "evaluatedValue": {
            "description": "評価額 (150% declining balance)",
            "example": 297500,
            "type": "number"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "location": {
            "example": "オフィス 3階",
            "type": "string"
          },
          "name": {
            "example": "業務用エアコン",
            "type": "string"
          },
          "openingBookValue": {
            "example": 350000,
            "type": "number"
          },
          "reason": {
            "example": "申告対象",
            "type": "string"
          },
          "remarks": {
            "nullable": true,
            "type": "string"
          },
          "taxCategory": {
            "description": "地方税法 category (1-6)",
            "example": 1,
            "type": "integer"
          },
          "taxCategoryName": {
            "example": "構築物",
            "type": "string"
          },
          "usefulLife": {
            "example": 15,
            "type": "integer"
          }
        },
        "type": "object"
      },
      "TeikanDocument": {
        "properties": {
          "created_at": {
            "description": "Creation timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "document_type": {
            "description": "Document type",
            "example": "teikan",
            "type": "string"
          },
          "id": {
            "description": "Document unique identifier",
            "example": "456e7890-f12a-34b5-c678-901234567890",
            "format": "uuid",
            "type": "string"
          },
          "status": {
            "description": "Document status",
            "enum": [
              "draft",
              "published",
              "archived"
            ],
            "example": "published",
            "type": "string"
          },
          "title": {
            "description": "Document title",
            "example": "定款",
            "type": "string"
          }
        },
        "required": [
          "id",
          "title",
          "document_type",
          "status",
          "created_at"
        ],
        "type": "object"
      },
      "TeikanDocumentListResponse": {
        "properties": {
          "data": {
            "items": {
              "$ref": "#/components/schemas/TeikanDocument"
            },
            "type": "array"
          },
          "message": {
            "example": "Available Teikan documents retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "TemplateResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/SimulationTemplate"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "type": "object"
      },
      "TestScriptCategory": {
        "description": "Test script category",
        "enum": [
          "rebuild",
          "test",
          "workflow",
          "analysis"
        ],
        "example": "test",
        "type": "string"
      },
      "TestScriptExecution": {
        "properties": {
          "companyId": {
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "createdAt": {
            "format": "date-time",
            "type": "string"
          },
          "dataContext": {
            "nullable": true,
            "type": "string"
          },
          "errors": {
            "items": {
              "type": "object"
            },
            "type": "array"
          },
          "executedAt": {
            "format": "date-time",
            "type": "string"
          },
          "executionTimeMs": {
            "nullable": true,
            "type": "integer"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "inputRecordCount": {
            "type": "integer"
          },
          "integrityCheckRunId": {
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "results": {
            "type": "object"
          },
          "scriptCategory": {
            "$ref": "#/components/schemas/TestScriptCategory"
          },
          "scriptId": {
            "type": "string"
          },
          "scriptName": {
            "type": "string"
          },
          "success": {
            "type": "boolean"
          },
          "userId": {
            "format": "uuid",
            "type": "string"
          },
          "warnings": {
            "items": {
              "type": "object"
            },
            "type": "array"
          }
        },
        "type": "object"
      },
      "TestScriptExecutionResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/TestScriptExecution"
          },
          "message": {
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "type": "object"
      },
      "TileCoordinates": {
        "properties": {
          "x": {
            "description": "Tile X coordinate",
            "example": 7274,
            "minimum": 0,
            "type": "integer"
          },
          "y": {
            "description": "Tile Y coordinate",
            "example": 3225,
            "minimum": 0,
            "type": "integer"
          },
          "z": {
            "description": "Zoom level",
            "example": 13,
            "maximum": 22,
            "minimum": 0,
            "type": "integer"
          }
        },
        "required": [
          "z",
          "x",
          "y"
        ],
        "type": "object"
      },
      "TileInfo": {
        "allOf": [
          {
            "$ref": "#/components/schemas/TileCoordinates"
          },
          {
            "properties": {
              "bounds": {
                "$ref": "#/components/schemas/Bounds",
                "description": "Geographic bounds of this tile"
              }
            },
            "required": [
              "bounds"
            ],
            "type": "object"
          }
        ]
      },
      "TileRequest": {
        "properties": {
          "x": {
            "description": "Tile X coordinate",
            "example": 7274,
            "minimum": 0,
            "type": "integer"
          },
          "y": {
            "description": "Tile Y coordinate",
            "example": 3225,
            "minimum": 0,
            "type": "integer"
          },
          "z": {
            "description": "Zoom level",
            "example": 13,
            "maximum": 22,
            "minimum": 0,
            "type": "integer"
          }
        },
        "required": [
          "z",
          "x",
          "y"
        ],
        "type": "object"
      },
      "TileResult": {
        "properties": {
          "cached": {
            "description": "Whether data was served from cache",
            "example": true,
            "type": "boolean"
          },
          "clustered": {
            "description": "Whether points were clustered",
            "example": false,
            "type": "boolean"
          },
          "data": {
            "description": "GeoJSON data or null if failed",
            "example": {
              "features": [],
              "type": "FeatureCollection"
            },
            "type": "object"
          },
          "error": {
            "description": "Error message if tile failed to load",
            "example": "Network timeout",
            "type": "string"
          },
          "simplified": {
            "description": "Whether geometry was simplified",
            "example": true,
            "type": "boolean"
          },
          "x": {
            "description": "Tile X coordinate",
            "example": 7274,
            "type": "integer"
          },
          "y": {
            "description": "Tile Y coordinate",
            "example": 3225,
            "type": "integer"
          },
          "z": {
            "description": "Zoom level",
            "example": 13,
            "type": "integer"
          }
        },
        "required": [
          "z",
          "x",
          "y",
          "data",
          "cached"
        ],
        "type": "object"
      },
      "TileWithBounds": {
        "allOf": [
          {
            "$ref": "#/components/schemas/TileCoordinates"
          },
          {
            "properties": {
              "bounds": {
                "$ref": "#/components/schemas/Bounds"
              }
            },
            "type": "object"
          }
        ]
      },
      "TilesForBoundsResponse": {
        "properties": {
          "data": {
            "properties": {
              "bounds": {
                "$ref": "#/components/schemas/Bounds",
                "description": "Input bounds"
              },
              "coverage": {
                "properties": {
                  "area": {
                    "example": "2x2 tiles",
                    "type": "string"
                  },
                  "xRange": {
                    "example": "7274-7275",
                    "type": "string"
                  },
                  "yRange": {
                    "example": "3225-3226",
                    "type": "string"
                  }
                },
                "type": "object"
              },
              "tiles": {
                "description": "Array of tiles covering the bounds",
                "items": {
                  "$ref": "#/components/schemas/TileWithBounds"
                },
                "type": "array"
              },
              "totalTiles": {
                "description": "Total number of tiles",
                "example": 4,
                "type": "integer"
              },
              "zoom": {
                "description": "Zoom level",
                "example": 13,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "TilesToBoundsResponse": {
        "properties": {
          "data": {
            "properties": {
              "bounds": {
                "$ref": "#/components/schemas/Bounds"
              },
              "center": {
                "$ref": "#/components/schemas/Coordinates",
                "description": "Center point of the tile"
              },
              "tile": {
                "$ref": "#/components/schemas/TileCoordinates"
              }
            },
            "type": "object"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "TimestampRequest": {
        "properties": {
          "document_id": {
            "description": "Document ID to timestamp",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "file_base64": {
            "description": "Base64 encoded file content for hash calculation",
            "example": "JVBERi0xLjQKJcfsj6IKNSAwIG9iago8PAovTGVuZ3RoIDYgMCBSCi9GaWx0ZXIgL0ZsYXRlRGVjb2RlCj4+",
            "format": "base64",
            "type": "string"
          }
        },
        "required": [
          "document_id"
        ],
        "type": "object"
      },
      "TimestampResponse": {
        "properties": {
          "data": {
            "properties": {
              "documentId": {
                "example": "123e4567-e89b-12d3-a456-426614174000",
                "format": "uuid",
                "type": "string"
              },
              "timestamp": {
                "example": "2024-03-15T10:30:00.000Z",
                "format": "date-time",
                "type": "string"
              },
              "token": {
                "example": "ts_a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3",
                "type": "string"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "タイムスタンプを付与しました",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "TimestampVerifyRequest": {
        "properties": {
          "document_id": {
            "description": "Document ID to verify",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "file_base64": {
            "description": "Base64 encoded file content for verification",
            "example": "JVBERi0xLjQKJcfsj6IKNSAwIG9iago8PAovTGVuZ3RoIDYgMCBSCi9GaWx0ZXIgL0ZsYXRlRGVjb2RlCj4+",
            "format": "base64",
            "type": "string"
          }
        },
        "required": [
          "document_id",
          "file_base64"
        ],
        "type": "object"
      },
      "TimestampVerifyResponse": {
        "properties": {
          "data": {
            "properties": {
              "isValid": {
                "description": "Whether timestamp is valid",
                "example": true,
                "type": "boolean"
              },
              "message": {
                "description": "Verification result message",
                "example": "タイムスタンプは有効です",
                "type": "string"
              }
            },
            "type": "object"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "TokenDebugResponse": {
        "properties": {
          "formatValidation": {
            "properties": {
              "error": {
                "example": null,
                "nullable": true,
                "type": "string"
              },
              "isValid": {
                "example": true,
                "type": "boolean"
              },
              "payload": {
                "nullable": true,
                "properties": {
                  "aud": {
                    "example": "authenticated",
                    "type": "string"
                  },
                  "email": {
                    "example": "user@example.com",
                    "type": "string"
                  },
                  "exp": {
                    "example": 1704067200,
                    "type": "number"
                  },
                  "expFormatted": {
                    "example": "2024-01-01T00:00:00.000Z",
                    "format": "date-time",
                    "type": "string"
                  },
                  "iat": {
                    "example": 1704063600,
                    "type": "number"
                  },
                  "iss": {
                    "example": "https://your-project.supabase.co/auth/v1",
                    "type": "string"
                  },
                  "role": {
                    "example": "authenticated",
                    "type": "string"
                  },
                  "sub": {
                    "example": "550e8400-e29b-41d4-a716-446655440000",
                    "type": "string"
                  }
                },
                "type": "object"
              }
            },
            "type": "object"
          },
          "headers": {
            "properties": {
              "correlationId": {
                "example": "abc123",
                "type": "string"
              },
              "hasCookieRefreshToken": {
                "example": true,
                "type": "boolean"
              },
              "hasXRefreshToken": {
                "example": false,
                "type": "boolean"
              }
            },
            "type": "object"
          },
          "tokenLength": {
            "example": 1024,
            "type": "number"
          },
          "tokenPreview": {
            "example": "eyJhbGciOiJIUzI1NiIsInR5cC...last10chars",
            "type": "string"
          },
          "tokenProvided": {
            "example": true,
            "type": "boolean"
          }
        },
        "type": "object"
      },
      "TokenFormatValidationRequest": {
        "properties": {
          "token": {
            "description": "JWT token to validate",
            "example": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
            "type": "string"
          }
        },
        "required": [
          "token"
        ],
        "type": "object"
      },
      "TokenFormatValidationResponse": {
        "properties": {
          "error": {
            "nullable": true,
            "type": "string"
          },
          "isValid": {
            "example": true,
            "type": "boolean"
          },
          "payload": {
            "description": "Decoded JWT payload (if valid format)",
            "nullable": true,
            "type": "object"
          },
          "tokenLength": {
            "example": 1024,
            "type": "number"
          },
          "tokenPreview": {
            "example": "eyJhbGciOiJIUzI1NiIsInR5cC...",
            "type": "string"
          }
        },
        "type": "object"
      },
      "TokenType": {
        "description": "Mapbox token type",
        "enum": [
          "public",
          "secret",
          "unknown"
        ],
        "example": "public",
        "type": "string"
      },
      "TokenValidationResponse": {
        "properties": {
          "data": {
            "properties": {
              "expiresAt": {
                "description": "Token expiration Unix timestamp (seconds)",
                "example": 1704067200,
                "nullable": true,
                "type": "number"
              },
              "expiresIn": {
                "description": "Seconds until token expires",
                "example": 3540,
                "nullable": true,
                "type": "number"
              },
              "userId": {
                "description": "Authenticated user ID",
                "example": "550e8400-e29b-41d4-a716-446655440000",
                "format": "uuid",
                "type": "string"
              },
              "valid": {
                "description": "Whether the token is valid",
                "example": true,
                "type": "boolean"
              }
            },
            "required": [
              "valid",
              "userId"
            ],
            "type": "object"
          },
          "message": {
            "example": "Token validated successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "TokenVerifyResponse": {
        "properties": {
          "authenticated": {
            "example": true,
            "type": "boolean"
          },
          "isDemo": {
            "example": false,
            "type": "boolean"
          },
          "message": {
            "example": "Token is valid and user is authenticated",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          },
          "user": {
            "properties": {
              "created_at": {
                "format": "date-time",
                "type": "string"
              },
              "email": {
                "example": "user@example.com",
                "format": "email",
                "type": "string"
              },
              "id": {
                "example": "550e8400-e29b-41d4-a716-446655440000",
                "format": "uuid",
                "type": "string"
              },
              "last_sign_in_at": {
                "format": "date-time",
                "type": "string"
              },
              "role": {
                "example": "authenticated",
                "type": "string"
              }
            },
            "type": "object"
          }
        },
        "type": "object"
      },
      "TourCompletion": {
        "description": "Tour completion status tracking for onboarding guides",
        "properties": {
          "ai_usage_tour": {
            "$ref": "#/components/schemas/TourCompletionStatus",
            "description": "AI usage tour (AI利用ツアー)"
          },
          "bank_reconciliation_tour": {
            "$ref": "#/components/schemas/TourCompletionStatus",
            "description": "Bank reconciliation tour (銀行照合ツアー)"
          },
          "bank_statement_tour": {
            "$ref": "#/components/schemas/TourCompletionStatus",
            "description": "Bank statement page tour (銀行取引ツアー)"
          },
          "expense_reports_tour": {
            "$ref": "#/components/schemas/TourCompletionStatus",
            "description": "Expense reports page tour (経費精算ツアー)"
          },
          "financial_reports_tour": {
            "$ref": "#/components/schemas/TourCompletionStatus",
            "description": "Financial reports tour (財務報告ツアー)"
          },
          "general_ledger_tour": {
            "$ref": "#/components/schemas/TourCompletionStatus",
            "description": "General ledger tour (総勘定元帳ツアー)"
          },
          "homepage_tour": {
            "$ref": "#/components/schemas/TourCompletionStatus",
            "description": "Homepage tour completion status (ホームページツアー)"
          },
          "kpi_dashboard_tour": {
            "$ref": "#/components/schemas/TourCompletionStatus",
            "description": "KPI dashboard tour (KPIダッシュボードツアー)"
          },
          "settings_tour": {
            "$ref": "#/components/schemas/TourCompletionStatus",
            "description": "Settings page tour (設定ツアー)"
          },
          "tax_compliance_tour": {
            "$ref": "#/components/schemas/TourCompletionStatus",
            "description": "Tax compliance tour (税務コンプライアンスツアー)"
          },
          "trial_balance_tour": {
            "$ref": "#/components/schemas/TourCompletionStatus",
            "description": "Trial balance tour (試算表ツアー)"
          },
          "welcome_guide": {
            "$ref": "#/components/schemas/TourCompletionStatus",
            "description": "Welcome guide completion status"
          },
          "withholding_tax_tour": {
            "$ref": "#/components/schemas/TourCompletionStatus",
            "description": "Withholding tax tour (源泉徴収ツアー)"
          }
        },
        "type": "object"
      },
      "TourCompletionStatus": {
        "description": "Completion status for a single tour/guide",
        "properties": {
          "completed": {
            "description": "Whether the tour has been completed",
            "example": true,
            "type": "boolean"
          },
          "completed_at": {
            "description": "ISO timestamp when the tour was completed",
            "example": "2026-01-30T20:44:00.000Z",
            "format": "date-time",
            "type": "string"
          }
        },
        "type": "object"
      },
      "TransactionAnalysis": {
        "description": "AI-powered transaction analysis from description (v4.29). Detects counterparty type and suggests accounts.",
        "properties": {
          "counterpartyName": {
            "description": "Extracted counterparty name from transaction description (摘要)",
            "example": "サンプルシヨウジ",
            "type": "string"
          },
          "counterpartyType": {
            "description": "Counterparty type classification based on pattern matching",
            "enum": [
              "company",
              "individual",
              "bank",
              "government",
              "unknown"
            ],
            "example": "company",
            "type": "string"
          },
          "detectedType": {
            "description": "Detected transaction type based on entry accounts",
            "enum": [
              "income",
              "expense",
              "transfer",
              "reimbursement",
              "suspense",
              "unknown"
            ],
            "example": "income",
            "type": "string"
          },
          "isCompanyName": {
            "description": "Whether counterparty appears to be a company (株式会社, （カ, etc.)",
            "example": true,
            "type": "boolean"
          },
          "suggestedAccountCode": {
            "description": "Suggested account code based on analysis",
            "example": "4100",
            "type": "string"
          },
          "suggestedAccountName": {
            "description": "Suggested account name based on analysis",
            "example": "売上高",
            "type": "string"
          }
        },
        "required": [
          "detectedType",
          "isCompanyName"
        ],
        "type": "object"
      },
      "TransactionCategory": {
        "description": "Transaction category classification for financial reporting",
        "enum": [
          0,
          1,
          2,
          3,
          4,
          5,
          6
        ],
        "example": 0,
        "type": "integer",
        "x-enum-varnames": [
          "SALES",
          "EXPENSE",
          "SALARY",
          "TAX",
          "TRANSFER",
          "LOANS",
          "OTHER"
        ]
      },
      "TransactionDetailsResponse": {
        "description": "Detailed transaction with document links and derived processing status",
        "properties": {
          "data": {
            "properties": {
              "derivedStatus": {
                "description": "Processing status information (v4.29+ includes explicit status support)",
                "properties": {
                  "derivedStatus": {
                    "description": "What status would be if derived from journal/document relationships",
                    "enum": [
                      "unprocessed",
                      "journal_only",
                      "doc_only",
                      "complete"
                    ],
                    "type": "string"
                  },
                  "explicitStatus": {
                    "description": "User-set explicit status (null if not set)",
                    "oneOf": [
                      {
                        "enum": [
                          "unprocessed",
                          "journal_only",
                          "doc_only",
                          "complete",
                          "no_doc_required"
                        ],
                        "type": "string"
                      },
                      {
                        "type": "null"
                      }
                    ]
                  },
                  "hasJournalEntry": {
                    "example": true,
                    "type": "boolean"
                  },
                  "hasLinkedDocument": {
                    "example": false,
                    "type": "boolean"
                  },
                  "isExplicit": {
                    "description": "Whether the effective status is from explicit setting (true) or derived (false)",
                    "example": false,
                    "type": "boolean"
                  },
                  "linkedDocumentCount": {
                    "example": 0,
                    "type": "integer"
                  },
                  "processingStatus": {
                    "description": "Effective status (explicit if set, otherwise derived from journal/document relationships)",
                    "enum": [
                      "unprocessed",
                      "journal_only",
                      "doc_only",
                      "complete",
                      "no_doc_required"
                    ],
                    "type": "string"
                  }
                },
                "type": "object"
              },
              "documentLinks": {
                "description": "Linked documents via document_transaction_links",
                "items": {
                  "properties": {
                    "aiReasoning": {
                      "nullable": true,
                      "type": "string"
                    },
                    "allocatedAmount": {
                      "nullable": true,
                      "type": "number"
                    },
                    "createdAt": {
                      "format": "date-time",
                      "type": "string"
                    },
                    "document": {
                      "nullable": true,
                      "properties": {
                        "amount": {
                          "nullable": true,
                          "type": "number"
                        },
                        "id": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "issueDate": {
                          "nullable": true,
                          "type": "integer"
                        },
                        "name": {
                          "example": "receipt_amazon_jan2026.pdf",
                          "type": "string"
                        },
                        "status": {
                          "type": "string"
                        },
                        "type": {
                          "example": "receipt",
                          "type": "string"
                        },
                        "vendorName": {
                          "nullable": true,
                          "type": "string"
                        }
                      },
                      "type": "object"
                    },
                    "documentId": {
                      "format": "uuid",
                      "type": "string"
                    },
                    "documentType": {
                      "example": "receipt",
                      "type": "string"
                    },
                    "linkId": {
                      "format": "uuid",
                      "type": "string"
                    },
                    "linkageType": {
                      "example": "direct_expense",
                      "type": "string"
                    },
                    "matchConfidence": {
                      "example": 0.95,
                      "nullable": true,
                      "type": "number"
                    },
                    "matchMethod": {
                      "enum": [
                        "manual",
                        "ai_suggested",
                        "auto_matched",
                        "rule_based"
                      ],
                      "type": "string"
                    },
                    "note": {
                      "nullable": true,
                      "type": "string"
                    }
                  },
                  "type": "object"
                },
                "type": "array"
              },
              "journalEntry": {
                "description": "Linked journal entry if exists",
                "nullable": true,
                "properties": {
                  "description": {
                    "type": "string"
                  },
                  "entryDate": {
                    "example": 20260115,
                    "type": "integer"
                  },
                  "id": {
                    "format": "uuid",
                    "type": "string"
                  },
                  "lines": {
                    "items": {
                      "properties": {
                        "accountCode": {
                          "example": "6230",
                          "type": "string"
                        },
                        "accountName": {
                          "example": "通信費",
                          "type": "string"
                        },
                        "creditAmount": {
                          "type": "number"
                        },
                        "debitAmount": {
                          "type": "number"
                        },
                        "description": {
                          "nullable": true,
                          "type": "string"
                        },
                        "id": {
                          "format": "uuid",
                          "type": "string"
                        }
                      },
                      "type": "object"
                    },
                    "type": "array"
                  },
                  "status": {
                    "type": "string"
                  }
                },
                "type": "object"
              },
              "transaction": {
                "description": "Core transaction data",
                "properties": {
                  "balance": {
                    "example": 1250000,
                    "type": "number"
                  },
                  "bankAccount": {
                    "nullable": true,
                    "properties": {
                      "accountNumber": {
                        "example": "1234567",
                        "type": "string"
                      },
                      "bankName": {
                        "example": "三菱UFJ銀行",
                        "type": "string"
                      },
                      "branchName": {
                        "example": "渋谷支店",
                        "type": "string"
                      },
                      "id": {
                        "format": "uuid",
                        "type": "string"
                      }
                    },
                    "type": "object"
                  },
                  "depositAmount": {
                    "example": 0,
                    "type": "number"
                  },
                  "description": {
                    "example": "アマゾン ジャパン",
                    "type": "string"
                  },
                  "id": {
                    "format": "uuid",
                    "type": "string"
                  },
                  "journalEntryId": {
                    "format": "uuid",
                    "nullable": true,
                    "type": "string"
                  },
                  "memo": {
                    "nullable": true,
                    "type": "string"
                  },
                  "reconciledAt": {
                    "format": "date-time",
                    "nullable": true,
                    "type": "string"
                  },
                  "reconciliationMethod": {
                    "nullable": true,
                    "type": "string"
                  },
                  "reconciliationStatus": {
                    "enum": [
                      "pending",
                      "matched",
                      "partially_matched",
                      "excluded",
                      "suspense"
                    ],
                    "type": "string"
                  },
                  "transactionDate": {
                    "example": 20260115,
                    "type": "integer"
                  },
                  "withdrawalAmount": {
                    "example": 12800,
                    "type": "number"
                  }
                },
                "type": "object"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Transaction details retrieved",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "type": "object"
      },
      "TransactionHistoryItem": {
        "properties": {
          "amounts": {
            "description": "Historical amounts",
            "example": [
              15000,
              12000,
              18000
            ],
            "items": {
              "format": "decimal",
              "type": "number"
            },
            "type": "array"
          },
          "currentCategory": {
            "description": "Current categorization (if any)",
            "example": "消耗品費",
            "type": "string"
          },
          "dates": {
            "description": "Historical dates",
            "example": [
              "2024-01-15",
              "2024-02-10",
              "2024-03-05"
            ],
            "items": {
              "format": "date",
              "type": "string"
            },
            "type": "array"
          },
          "description": {
            "description": "Transaction description pattern",
            "example": "Amazon",
            "type": "string"
          }
        },
        "required": [
          "description",
          "amounts",
          "dates"
        ],
        "type": "object"
      },
      "TransactionInput": {
        "properties": {
          "amount": {
            "description": "Transaction amount",
            "example": 15000,
            "format": "decimal",
            "type": "number"
          },
          "bankAccountId": {
            "description": "Bank account identifier (optional)",
            "example": "acc_789",
            "type": "string"
          },
          "date": {
            "description": "Transaction date",
            "example": "2024-03-15",
            "format": "date",
            "type": "string"
          },
          "description": {
            "description": "Transaction description",
            "example": "オフィス用品購入 - Amazon",
            "type": "string"
          },
          "id": {
            "description": "Unique transaction identifier",
            "example": "txn_123456",
            "type": "string"
          },
          "type": {
            "$ref": "#/components/schemas/TransactionType"
          }
        },
        "required": [
          "id",
          "description",
          "amount",
          "date",
          "type"
        ],
        "type": "object"
      },
      "TransactionIntegrityResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/TransactionIntegrityStatus"
          },
          "message": {
            "example": "取引の整合性情報を取得しました",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "TransactionIntegrityStatus": {
        "properties": {
          "hasViolations": {
            "description": "Whether transaction has integrity violations",
            "example": false,
            "type": "boolean"
          },
          "integrityScore": {
            "description": "Integrity score (0.0 to 1.0)",
            "example": 0.95,
            "format": "double",
            "type": "number"
          },
          "lastCheckedAt": {
            "description": "Last integrity check timestamp",
            "example": "2024-03-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "transactionId": {
            "description": "Transaction ID",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "violationCount": {
            "description": "Number of violations for this transaction",
            "example": 0,
            "type": "integer"
          },
          "violations": {
            "description": "List of violations for this transaction",
            "items": {
              "$ref": "#/components/schemas/IntegrityViolation"
            },
            "type": "array"
          }
        },
        "required": [
          "transactionId",
          "integrityScore",
          "hasViolations",
          "violationCount",
          "lastCheckedAt",
          "violations"
        ],
        "type": "object"
      },
      "TransactionLinkedCount": {
        "description": "Document link count, status, and fixed asset info for a single bank transaction",
        "properties": {
          "documentCount": {
            "description": "Number of documents linked to this transaction",
            "example": 2,
            "minimum": 0,
            "type": "integer"
          },
          "fixedAssetId": {
            "description": "UUID of the linked fixed asset (v4.50+, only present if hasFixedAsset is true)",
            "example": "550e8400-e29b-41d4-a716-446655440001",
            "format": "uuid",
            "type": "string"
          },
          "fixedAssetName": {
            "description": "Name of the linked fixed asset (v4.50+, only present if hasFixedAsset is true)",
            "example": "スズキ ジムニー シエラ（JB74W）",
            "type": "string"
          },
          "hasFixedAsset": {
            "description": "Whether a fixed asset is linked to this transaction (v4.50+)",
            "example": true,
            "type": "boolean"
          },
          "hasJournal": {
            "description": "Whether a journal entry is linked to this transaction",
            "example": true,
            "type": "boolean"
          },
          "processingStatus": {
            "description": "Effective processing status. If explicit status is set, uses that. Otherwise derives from journal/document relationships.",
            "enum": [
              "unprocessed",
              "journal_only",
              "doc_only",
              "complete",
              "no_doc_required",
              "fixed_asset",
              "fixed_asset_registered"
            ],
            "example": "complete",
            "type": "string"
          },
          "suggestConfidence": {
            "description": "Confidence score for the suggestion (v4.34+)",
            "example": 0.95,
            "maximum": 1,
            "minimum": 0,
            "type": "number"
          },
          "suggestReason": {
            "description": "Japanese explanation of why this status is suggested (v4.34+)",
            "example": "利息取引は通常証憑不要（通帳で確認可能）",
            "type": "string"
          },
          "suggestedStatus": {
            "description": "AI-suggested status for unprocessed transactions (v4.34+). Only present if a pattern match is found.",
            "enum": [
              "no_doc_required"
            ],
            "example": "no_doc_required",
            "type": "string"
          }
        },
        "required": [
          "documentCount",
          "hasJournal",
          "processingStatus",
          "hasFixedAsset"
        ],
        "type": "object"
      },
      "TransactionTemplateItem": {
        "properties": {
          "category": {
            "example": "資本取引",
            "type": "string"
          },
          "creditAccount": {
            "example": "資本金",
            "type": "string"
          },
          "debitAccount": {
            "example": "現金及び預金",
            "type": "string"
          },
          "defaultAmount": {
            "example": 3000000,
            "type": "number"
          },
          "description": {
            "type": "string"
          },
          "id": {
            "example": "capital-investment",
            "type": "string"
          },
          "name": {
            "example": "資本金設立",
            "type": "string"
          }
        },
        "type": "object"
      },
      "TransactionType": {
        "description": "Bank transaction type",
        "enum": [
          "deposit",
          "withdrawal"
        ],
        "example": "withdrawal",
        "type": "string"
      },
      "TransactionWithBankAccount": {
        "allOf": [
          {
            "$ref": "#/components/schemas/TransactionInput"
          },
          {
            "properties": {
              "bankAccount": {
                "$ref": "#/components/schemas/BankAccountInput"
              }
            },
            "required": [
              "bankAccount"
            ],
            "type": "object"
          }
        ]
      },
      "TransferGuard": {
        "description": "What the pay dialog showed when the owner confirmed the transfer (computed client-side from the latest bank balance and known obligations; the server validates and records it on the 支払明細書)",
        "properties": {
          "balance": {
            "nullable": true,
            "type": "integer"
          },
          "balance_as_of": {
            "description": "YYYYMMDD of the latest bank row",
            "nullable": true,
            "type": "integer"
          },
          "obligations_total": {
            "type": "integer"
          },
          "short": {
            "description": "The transfer exceeds balance − obligations",
            "type": "boolean"
          },
          "short_override_note": {
            "description": "Required (4+ characters) when short: the expected deposit that covers it",
            "maxLength": 200,
            "type": "string"
          },
          "stale_acknowledged_as_of": {
            "description": "YYYYMMDD the owner confirmed as current when the latest bank row is older than 3 days",
            "type": "integer"
          },
          "transfer_total": {
            "type": "integer"
          }
        },
        "required": [
          "balance",
          "balance_as_of",
          "obligations_total",
          "transfer_total",
          "short"
        ],
        "type": "object"
      },
      "TravelReportSummary": {
        "properties": {
          "attachmentCount": {
            "description": "Number of attached receipts and documents",
            "example": 12,
            "type": "integer"
          },
          "currency": {
            "description": "Currency code",
            "example": "JPY",
            "type": "string"
          },
          "expenseCount": {
            "description": "Number of expenses in travel report",
            "example": 8,
            "type": "integer"
          },
          "hasInkan": {
            "$ref": "#/components/schemas/DockHasInkan"
          },
          "id": {
            "description": "Travel report document identifier",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "name": {
            "description": "Travel report document name",
            "example": "2024年1月出張報告書 - 東京営業所",
            "type": "string"
          },
          "status": {
            "description": "Document status",
            "enum": [
              "draft",
              "published",
              "archived"
            ],
            "example": "published",
            "type": "string"
          },
          "totalAmount": {
            "description": "Total travel expenses amount",
            "example": 45000,
            "type": "number"
          },
          "tripDays": {
            "description": "Number of days in business trip",
            "example": 3,
            "type": "integer"
          },
          "type": {
            "description": "Document type (travel)",
            "example": "travel",
            "type": "string"
          }
        },
        "required": [
          "id",
          "name",
          "type",
          "totalAmount",
          "currency",
          "status",
          "expenseCount",
          "attachmentCount",
          "tripDays"
        ],
        "type": "object"
      },
      "TrendDirection": {
        "description": "Trend direction for KPI metrics",
        "enum": [
          "up",
          "down",
          "stable"
        ],
        "example": "up",
        "type": "string"
      },
      "TrialBalanceLine": {
        "properties": {
          "accountCode": {
            "description": "Account code for identification",
            "example": "1001",
            "type": "string"
          },
          "accountName": {
            "description": "Account name in Japanese",
            "example": "現金",
            "type": "string"
          },
          "category": {
            "description": "Account category/type",
            "enum": [
              "asset",
              "liability",
              "equity",
              "revenue",
              "expense"
            ],
            "example": "asset",
            "type": "string"
          },
          "closingCredit": {
            "description": "Closing credit balance (期末貸方残高)",
            "example": 0,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "closingDebit": {
            "description": "Closing debit balance (期末借方残高)",
            "example": 700000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "openingCredit": {
            "description": "Opening credit balance (期首貸方残高)",
            "example": 0,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "openingDebit": {
            "description": "Opening debit balance (期首借方残高)",
            "example": 500000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "periodCredit": {
            "description": "Period credit activity (当期貸方発生額)",
            "example": 100000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "periodDebit": {
            "description": "Period debit activity (当期借方発生額)",
            "example": 300000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "priorPeriodCredit": {
            "description": "Prior period credit activity (前期貸方発生額)",
            "example": 50000,
            "format": "decimal",
            "minimum": 0,
            "nullable": true,
            "type": "number"
          },
          "priorPeriodDebit": {
            "description": "Prior period debit activity (前期借方発生額)",
            "example": 250000,
            "format": "decimal",
            "minimum": 0,
            "nullable": true,
            "type": "number"
          },
          "variance": {
            "description": "Variance from prior period (前期差異)",
            "example": 100000,
            "format": "decimal",
            "nullable": true,
            "type": "number"
          },
          "variancePercent": {
            "description": "Variance percentage from prior period (前期差異率)",
            "example": 50,
            "format": "decimal",
            "nullable": true,
            "type": "number"
          }
        },
        "required": [
          "accountCode",
          "accountName",
          "category",
          "openingDebit",
          "openingCredit",
          "periodDebit",
          "periodCredit",
          "closingDebit",
          "closingCredit"
        ],
        "type": "object"
      },
      "TrialBalanceReport": {
        "properties": {
          "generatedAt": {
            "description": "Report generation timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "isBalanced": {
            "description": "Whether the trial balance is balanced (debits = credits)",
            "example": true,
            "type": "boolean"
          },
          "lines": {
            "description": "Trial balance lines for each account",
            "items": {
              "$ref": "#/components/schemas/TrialBalanceLine"
            },
            "type": "array"
          },
          "periodEnd": {
            "description": "Period end date (YYYY-MM-DD format)",
            "example": "2024-12-31",
            "type": "string"
          },
          "periodStart": {
            "description": "Period start date (YYYY-MM-DD format)",
            "example": "2024-04-01",
            "type": "string"
          },
          "priorPeriodEnd": {
            "description": "Prior period end date (YYYY-MM-DD format)",
            "example": "2023-12-31",
            "nullable": true,
            "type": "string"
          },
          "priorPeriodStart": {
            "description": "Prior period start date (YYYY-MM-DD format)",
            "example": "2023-04-01",
            "nullable": true,
            "type": "string"
          },
          "totals": {
            "$ref": "#/components/schemas/TrialBalanceTotals",
            "description": "Aggregated totals for all accounts"
          }
        },
        "required": [
          "periodStart",
          "periodEnd",
          "lines",
          "totals",
          "isBalanced",
          "generatedAt"
        ],
        "type": "object"
      },
      "TrialBalanceResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/TrialBalanceReport"
          },
          "message": {
            "example": "Trial balance generated successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "TrialBalanceTotals": {
        "properties": {
          "closingCredit": {
            "description": "Total closing credit balances (期末貸方残高合計)",
            "example": 5500000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "closingDebit": {
            "description": "Total closing debit balances (期末借方残高合計)",
            "example": 5500000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "openingCredit": {
            "description": "Total opening credit balances (期首貸方残高合計)",
            "example": 5000000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "openingDebit": {
            "description": "Total opening debit balances (期首借方残高合計)",
            "example": 5000000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "periodCredit": {
            "description": "Total period credit activity (当期貸方発生額合計)",
            "example": 2500000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "periodDebit": {
            "description": "Total period debit activity (当期借方発生額合計)",
            "example": 2500000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "priorPeriodCredit": {
            "description": "Total prior period credit activity (前期貸方発生額合計)",
            "example": 2000000,
            "format": "decimal",
            "minimum": 0,
            "nullable": true,
            "type": "number"
          },
          "priorPeriodDebit": {
            "description": "Total prior period debit activity (前期借方発生額合計)",
            "example": 2000000,
            "format": "decimal",
            "minimum": 0,
            "nullable": true,
            "type": "number"
          }
        },
        "required": [
          "openingDebit",
          "openingCredit",
          "periodDebit",
          "periodCredit",
          "closingDebit",
          "closingCredit"
        ],
        "type": "object"
      },
      "UiPreferences": {
        "description": "Cross-device UI preferences synced from `user_profiles.ui_preferences`. Drives mobile-bottom-dock pinning, table layout overrides, density theme, font scale, reduced-motion, native haptics, mobile formatting, swipe actions, and mobile home composition.",
        "properties": {
          "amount_format": {
            "enum": [
              "compact",
              "full"
            ],
            "example": "full",
            "type": "string"
          },
          "color_scheme": {
            "enum": [
              "system",
              "light",
              "dark"
            ],
            "example": "system",
            "type": "string"
          },
          "currency_symbol": {
            "enum": [
              "¥",
              "JPY",
              "円"
            ],
            "example": "¥",
            "type": "string"
          },
          "date_format": {
            "enum": [
              "iso",
              "jp-wareki",
              "jp-seireki"
            ],
            "example": "jp-seireki",
            "type": "string"
          },
          "density": {
            "description": "Density token (matches `data-density` cascade)",
            "enum": [
              "default",
              "comfortable",
              "compact",
              "ja-compact",
              "ultra"
            ],
            "example": "ultra",
            "type": "string"
          },
          "dock_hidden": {
            "description": "Mobile dock feature ids hidden by the user",
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "dock_pin": {
            "description": "Ordered list of pinned MobileBottomDock feature keys",
            "example": [
              "scan",
              "documents",
              "tax-journal"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "font_scale": {
            "description": "Body-text scale multiplier; clamped 0.85..1.4 server-side",
            "example": 1,
            "type": "number"
          },
          "haptics": {
            "description": "Native/PWA haptic feedback preference",
            "properties": {
              "enabled": {
                "example": true,
                "type": "boolean"
              },
              "intensity": {
                "enum": [
                  "light",
                  "medium",
                  "heavy"
                ],
                "example": "light",
                "type": "string"
              }
            },
            "type": "object"
          },
          "home_feed_order": {
            "description": "Ordered mobile home feed/widget ids",
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "home_shortcuts": {
            "description": "Ordered home 「よく使う」 shortcut ids (desktop home fold)",
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "large_text": {
            "enum": [
              1,
              1.15,
              1.3
            ],
            "example": 1,
            "type": "number"
          },
          "quick_actions_mobile": {
            "description": "Ordered homepage quick actions on mobile",
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "reduced_motion": {
            "description": "Honor reduced-motion preference in UI animations",
            "example": false,
            "type": "boolean"
          },
          "share_link_expiry_days": {
            "description": "Default lifetime of a new public document share link in days; null = never expires",
            "example": 30,
            "maximum": 3650,
            "minimum": 1,
            "nullable": true,
            "type": "integer"
          },
          "swipe_actions": {
            "additionalProperties": {
              "properties": {
                "left": {
                  "type": "string"
                },
                "right": {
                  "type": "string"
                }
              },
              "type": "object"
            },
            "description": "Per-list swipe action choices",
            "type": "object"
          },
          "table_layouts": {
            "additionalProperties": {
              "enum": [
                "cards",
                "priority",
                "scroll-frozen"
              ],
              "type": "string"
            },
            "description": "Per-table mobile layout override keyed by stable table id",
            "example": {
              "homepage.documents": "priority",
              "tax-journal.entries": "scroll-frozen"
            },
            "type": "object"
          },
          "table_pinned_columns": {
            "additionalProperties": {
              "items": {
                "type": "string"
              },
              "type": "array"
            },
            "description": "Per-table mobile pinned column ids",
            "type": "object"
          }
        },
        "type": "object"
      },
      "UiPreferencesResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/UiPreferences"
          },
          "message": {
            "example": "UI preferences retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "UnlinkDocumentsRequest": {
        "properties": {
          "source_document_id": {
            "description": "Source document ID in the relationship",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "target_document_id": {
            "description": "Target document ID in the relationship",
            "example": "456e7890-f12a-34b5-c678-901234567890",
            "format": "uuid",
            "type": "string"
          },
          "workflow_type": {
            "$ref": "#/components/schemas/ReimbursementWorkflowType",
            "description": "Type of workflow relationship to unlink"
          }
        },
        "required": [
          "source_document_id",
          "target_document_id",
          "workflow_type"
        ],
        "type": "object"
      },
      "UnlockBooksShareRequest": {
        "properties": {
          "password": {
            "maxLength": 72,
            "minLength": 1,
            "type": "string"
          }
        },
        "required": [
          "password"
        ],
        "type": "object"
      },
      "UnlockBooksShareResponse": {
        "description": "Short-lived HMAC proof for subsequent requests (12h TTL)",
        "properties": {
          "proof": {
            "description": "v1.<shareId>.<exp>.<hmac> — send as X-Share-Proof header or ?proof= query param",
            "type": "string"
          },
          "proof_expires_at": {
            "format": "date-time",
            "type": "string"
          }
        },
        "type": "object"
      },
      "UnreadCountResponse": {
        "properties": {
          "data": {
            "properties": {
              "count": {
                "example": 5,
                "minimum": 0,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Unread count retrieved successfully",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "UnreconciledTransaction": {
        "properties": {
          "balance": {
            "description": "Account balance after transaction",
            "example": 1235000,
            "format": "decimal",
            "type": "number"
          },
          "bank_account_id": {
            "description": "Associated bank account ID",
            "example": "456e7890-f12a-34b5-c678-901234567890",
            "format": "uuid",
            "type": "string"
          },
          "counterparty_name": {
            "description": "Counterparty name (Japanese)",
            "example": "オフィス用品ストア",
            "nullable": true,
            "type": "string"
          },
          "days_unreconciled": {
            "description": "Days since transaction occurred",
            "example": 5,
            "minimum": 0,
            "type": "integer"
          },
          "deposit_amount": {
            "description": "Deposit amount in JPY",
            "example": 0,
            "format": "decimal",
            "type": "number"
          },
          "description": {
            "description": "Transaction description",
            "example": "カード決済 オフィス用品",
            "type": "string"
          },
          "id": {
            "description": "Bank transaction unique identifier",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "match_suggestions_count": {
            "description": "Number of available match suggestions",
            "example": 3,
            "minimum": 0,
            "type": "integer"
          },
          "status": {
            "$ref": "#/components/schemas/ReconciliationStatus"
          },
          "transaction_date": {
            "description": "Transaction date in YYYYMMDD format",
            "example": 20240115,
            "type": "integer"
          },
          "withdrawal_amount": {
            "description": "Withdrawal amount in JPY",
            "example": 15000,
            "format": "decimal",
            "type": "number"
          }
        },
        "required": [
          "id",
          "transaction_date",
          "description",
          "withdrawal_amount",
          "deposit_amount",
          "balance",
          "status",
          "match_suggestions_count",
          "days_unreconciled"
        ],
        "type": "object"
      },
      "UnreconciledTransactionsResponse": {
        "properties": {
          "data": {
            "properties": {
              "items": {
                "items": {
                  "$ref": "#/components/schemas/UnreconciledTransaction"
                },
                "type": "array"
              },
              "pagination": {
                "$ref": "#/components/schemas/Pagination"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Unreconciled transactions retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "UpdateAIPreferenceRequest": {
        "properties": {
          "account_code": {
            "type": "string"
          },
          "account_name": {
            "type": "string"
          },
          "description": {
            "type": "string"
          },
          "is_active": {
            "type": "boolean"
          },
          "pattern": {
            "type": "string"
          },
          "priority": {
            "type": "integer"
          },
          "tax_category": {
            "type": "string"
          }
        },
        "type": "object"
      },
      "UpdateAISettingsRequest": {
        "description": "AI settings update request",
        "properties": {
          "ai_settings": {
            "$ref": "#/components/schemas/AISettingsSchema",
            "description": "AI settings to update (optional)"
          }
        },
        "type": "object"
      },
      "UpdateAccountingConfigRequest": {
        "description": "Accounting configuration update request with Japanese tax compliance options",
        "properties": {
          "accounting_method": {
            "description": "Accounting method preference",
            "enum": [
              0,
              1
            ],
            "example": 0,
            "type": "integer"
          },
          "consumption_tax_method": {
            "description": "Consumption tax calculation method selection",
            "enum": [
              0,
              1,
              2,
              3
            ],
            "example": 0,
            "type": "integer"
          },
          "declaration_type": {
            "description": "Tax declaration type selection",
            "enum": [
              0,
              1
            ],
            "example": 0,
            "type": "integer"
          },
          "depreciation_method": {
            "description": "Asset depreciation method selection",
            "enum": [
              1,
              2,
              3,
              4
            ],
            "example": 1,
            "type": "integer"
          },
          "has_exempt_period": {
            "description": "Enable tax exemption period",
            "example": false,
            "type": "boolean"
          },
          "has_tax_payment_special_provision": {
            "description": "Enable special provision for tax payment",
            "example": false,
            "type": "boolean"
          },
          "tax_calculation": {
            "description": "Tax calculation basis selection",
            "enum": [
              0,
              1
            ],
            "example": 0,
            "type": "integer"
          },
          "taxation_type": {
            "description": "Taxation type classification",
            "enum": [
              0,
              1,
              2,
              3
            ],
            "example": 0,
            "type": "integer"
          }
        },
        "type": "object"
      },
      "UpdateAchievementRequest": {
        "properties": {
          "achievement_id": {
            "example": "document_creator",
            "maxLength": 50,
            "type": "string"
          },
          "progress": {
            "example": 25,
            "minimum": 0,
            "type": "integer"
          }
        },
        "required": [
          "achievement_id",
          "progress"
        ],
        "type": "object"
      },
      "UpdateApiKeyRequest": {
        "properties": {
          "apiKey": {
            "description": "OpenAI API key to store for the user",
            "example": "sk-proj-...",
            "pattern": "^sk-",
            "type": "string"
          }
        },
        "required": [
          "apiKey"
        ],
        "type": "object"
      },
      "UpdateBankAccountRequest": {
        "properties": {
          "account_holder_name": {
            "maxLength": 100,
            "type": "string"
          },
          "account_number": {
            "pattern": "^\\d{7,8}$",
            "type": "string"
          },
          "account_type": {
            "enum": [
              "普通",
              "当座",
              "貯蓄"
            ],
            "type": "string"
          },
          "bank_code": {
            "pattern": "^\\d{4}$",
            "type": "string"
          },
          "bank_name": {
            "maxLength": 100,
            "type": "string"
          },
          "branch_code": {
            "pattern": "^\\d{3}$",
            "type": "string"
          },
          "branch_name": {
            "maxLength": 50,
            "type": "string"
          },
          "display_name": {
            "maxLength": 100,
            "type": "string"
          },
          "is_primary": {
            "type": "boolean"
          },
          "loan_end_date": {
            "format": "date",
            "type": "string"
          },
          "loan_interest_rate": {
            "type": "number"
          },
          "loan_lender_name": {
            "maxLength": 100,
            "type": "string"
          },
          "loan_original_amount": {
            "minimum": 0,
            "type": "integer"
          },
          "loan_start_date": {
            "format": "date",
            "type": "string"
          },
          "loan_type": {
            "enum": [
              "bank",
              "director_to_company",
              "company_to_director",
              "policy",
              "other"
            ],
            "type": "string"
          },
          "purpose": {
            "enum": [
              "business",
              "personal",
              "reimbursement",
              "loan",
              "savings",
              "tax_payment",
              "payroll",
              "deposit",
              "other"
            ],
            "type": "string"
          },
          "sort_order": {
            "minimum": 0,
            "type": "integer"
          }
        },
        "type": "object"
      },
      "UpdateCategoryRuleRequest": {
        "properties": {
          "base_confidence": {
            "maximum": 0.98,
            "minimum": 0.3,
            "type": "number"
          },
          "is_active": {
            "type": "boolean"
          },
          "match_pattern": {
            "maxLength": 500,
            "minLength": 1,
            "type": "string"
          },
          "priority": {
            "maximum": 100,
            "minimum": 1,
            "type": "integer"
          },
          "rule_description": {
            "maxLength": 2000,
            "type": "string"
          },
          "rule_name": {
            "maxLength": 200,
            "type": "string"
          },
          "rule_type": {
            "$ref": "#/components/schemas/CategoryRuleType"
          },
          "secondary_pattern": {
            "maxLength": 500,
            "type": "string"
          },
          "suggested_category": {
            "maximum": 26,
            "minimum": 0,
            "type": "integer"
          }
        },
        "type": "object"
      },
      "UpdateClientRequest": {
        "description": "Partial update request - only include fields to update",
        "properties": {
          "address": {
            "description": "Company address",
            "example": "東京都渋谷区サンプル１丁目２番３号",
            "maxLength": 500,
            "nullable": true,
            "type": "string"
          },
          "client_type": {
            "description": "Client type (0=Customer, 1=Supplier, 2=Both)",
            "enum": [
              0,
              1,
              2
            ],
            "example": 0,
            "type": "number"
          },
          "contact_person": {
            "description": "Primary contact person name",
            "example": "山田太郎",
            "maxLength": 100,
            "type": "string"
          },
          "corporate_number": {
            "description": "Japanese corporate number (13 digits)",
            "example": "1234567890123",
            "pattern": "^\\d{13}$",
            "type": "string"
          },
          "email": {
            "description": "Contact email address",
            "example": "contact@example.co.jp",
            "format": "email",
            "maxLength": 254,
            "nullable": true,
            "type": "string"
          },
          "furigana": {
            "description": "Company name in katakana (furigana)",
            "example": "サンプルカブシキガイシャ",
            "maxLength": 200,
            "nullable": true,
            "type": "string"
          },
          "name": {
            "description": "Official client company name",
            "example": "サンプル株式会社",
            "maxLength": 200,
            "type": "string"
          },
          "phone": {
            "description": "Contact phone number",
            "example": "03-0000-0000",
            "maxLength": 20,
            "nullable": true,
            "type": "string"
          },
          "registration_number": {
            "description": "Invoice registration number (T + 13 digits)",
            "example": "T1234567890123",
            "nullable": true,
            "type": "string"
          }
        },
        "type": "object"
      },
      "UpdateClientSuccessResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/ClientResponse"
          },
          "message": {
            "example": "Client updated successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "UpdateCompanyRequest": {
        "properties": {
          "address2": {
            "description": "Secondary address line (建物名・階数等) - building name, floor, etc.",
            "example": "サクラビル5F",
            "maxLength": 255,
            "type": "string"
          },
          "business_objectives": {
            "description": "Business objectives (事業目的/目的) array. From 定款 article4.objectives.",
            "example": [
              "ソフトウェアの開発",
              "ITコンサルティング"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "capital": {
            "description": "Company capital in Japanese Yen",
            "example": 1000000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "corporate_number": {
            "description": "Japanese corporate number (法人番号) - 13 digits",
            "example": "1234567890123",
            "maxLength": 13,
            "minLength": 13,
            "pattern": "^[0-9]{13}$",
            "type": "string"
          },
          "executive_compensation": {
            "description": "Monthly executive compensation (役員報酬) in yen. From 定款 article17.",
            "example": 200000,
            "type": "integer"
          },
          "first_fiscal_year_end": {
            "description": "First fiscal year end (最初の事業年度末) in YYYYMMDD format. From 定款 article31.",
            "example": 20260215,
            "type": "integer"
          },
          "fiscal_year_end": {
            "description": "Fiscal year end date in MMDD format",
            "example": 331,
            "maximum": 1231,
            "minimum": 101,
            "type": "integer"
          },
          "fiscal_year_start": {
            "description": "Fiscal year start date in MMDD format",
            "example": 401,
            "maximum": 1231,
            "minimum": 101,
            "type": "integer"
          },
          "incorporation_date": {
            "description": "Company incorporation/establishment date (開業日) in YYYYMMDD format. Can be extracted from 定款 signature.date field (e.g., \"令和７年６月６日\" → 20250606). Used for first-year tax obligation calculations.",
            "example": 20250606,
            "type": "integer"
          },
          "is_multiple_workplace_employee": {
            "description": "Multiple workplace employee flag (二以上事業所勤務者).\nSet to true if this company is a secondary workplace (従たる給与) using 乙欄 tax table.\nSet to false (default) if this is the primary workplace (主たる給与) using 甲欄 tax table.\n\nImportant: 乙欄 users cannot perform 年末調整 and must file 確定申告.",
            "example": false,
            "type": "boolean"
          },
          "linked_document_id": {
            "description": "Linked Teikan document ID",
            "example": "456e7890-f12a-34b5-c678-901234567890",
            "format": "uuid",
            "type": "string"
          },
          "member_info": {
            "description": "Member/shareholder information (社員・出資情報). From 定款.",
            "properties": {
              "members": {
                "items": {
                  "properties": {
                    "address": {
                      "type": "string"
                    },
                    "capitalContribution": {
                      "type": "number"
                    },
                    "name": {
                      "type": "string"
                    }
                  },
                  "type": "object"
                },
                "type": "array"
              },
              "totalCapital": {
                "type": "number"
              }
            },
            "type": "object"
          },
          "name": {
            "description": "Company name in Japanese",
            "example": "株式会社ソロボス",
            "maxLength": 255,
            "type": "string"
          },
          "office_address": {
            "description": "Company office address in Japanese format",
            "example": "東京都渋谷区渋谷1-1-1",
            "maxLength": 255,
            "type": "string"
          },
          "phone_number": {
            "description": "Company phone number (電話番号). From 経費規定 companyInfo.tel.",
            "example": "070-8459-3512",
            "maxLength": 20,
            "type": "string"
          },
          "postal_code": {
            "description": "Postal code (郵便番号) in Japanese format XXX-XXXX",
            "example": "100-0001",
            "maxLength": 10,
            "type": "string"
          },
          "public_notice_method": {
            "description": "Public notice method (公告方法). From 定款 article3.",
            "example": "官報に掲載してする",
            "type": "string"
          },
          "representative": {
            "description": "Representative director name (代表取締役)",
            "example": "田中太郎",
            "maxLength": 255,
            "type": "string"
          },
          "social_insurance_multi_employer": {
            "description": "社会保険の二以上事業所勤務: the representative is also enrolled in 健康保険・厚生年金 at another company. null = not answered (the 算定基礎届 guidance then keeps its conditional wording). Not the income-tax 乙欄 flag.",
            "example": null,
            "nullable": true,
            "type": "boolean"
          }
        },
        "type": "object"
      },
      "UpdateCreditCardRequest": {
        "properties": {
          "brand": {
            "enum": [
              "VISA",
              "Mastercard",
              "JCB",
              "AMEX",
              "Diners"
            ],
            "type": "string"
          },
          "card_name": {
            "maxLength": 100,
            "type": "string"
          },
          "closing_day": {
            "maximum": 31,
            "minimum": 1,
            "nullable": true,
            "type": "integer"
          },
          "color": {
            "pattern": "^#[0-9A-Fa-f]{6}$",
            "type": "string"
          },
          "icon": {
            "maxLength": 50,
            "type": "string"
          },
          "is_active": {
            "type": "boolean"
          },
          "issuer": {
            "maxLength": 50,
            "type": "string"
          },
          "last_four_digits": {
            "pattern": "^\\d{4}$",
            "type": "string"
          },
          "linked_bank_account_id": {
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "notes": {
            "maxLength": 500,
            "type": "string"
          },
          "payment_day": {
            "maximum": 31,
            "minimum": 1,
            "nullable": true,
            "type": "integer"
          }
        },
        "type": "object"
      },
      "UpdateDependentInput": {
        "description": "Same fields as CreateDependentInput, all optional",
        "type": "object"
      },
      "UpdateDocumentRequest": {
        "properties": {
          "client_id": {
            "description": "Link document to a client (trading partner)",
            "example": "550e8400-e29b-41d4-a716-446655440000",
            "format": "uuid",
            "type": "string"
          },
          "content": {
            "additionalProperties": true,
            "description": "Document content (structured JSON)",
            "example": {
              "items": [
                {
                  "name": "Service",
                  "price": 1500,
                  "quantity": 2
                }
              ],
              "title": "Updated Sales Invoice",
              "total": 3000
            },
            "type": "object"
          },
          "document_name": {
            "description": "Document name",
            "example": "Updated Sales Invoice",
            "maxLength": 50,
            "type": "string"
          },
          "metadata": {
            "additionalProperties": true,
            "description": "Additional metadata for the document. **Uses DEEP MERGE** - nested objects are recursively merged, preserving properties you don't update.\n\n**Merge Behavior (v4.27):**\n- Objects: Recursively merged (nested properties preserved)\n- Arrays: Replaced entirely (not concatenated)\n- null: Explicitly sets value to null\n- undefined: Skips the property (no change)\n\n**Example:** If existing metadata is `{ aiAnalysis: { category: 'A', vendor: 'B' } }` and you update with `{ aiAnalysis: { category: 'C' } }`, the result is `{ aiAnalysis: { category: 'C', vendor: 'B' } }` - vendor is preserved!\n\n**Limits:**\n- Maximum size: 100KB\n- Maximum nesting depth: 10 levels\n- Prototype pollution protection enabled",
            "example": {
              "aiAnalysis": {
                "analyzedAt": "2026-01-15T10:30:00Z",
                "category": "経費",
                "confidence": 0.95,
                "extractedData": {
                  "amount": 15000,
                  "date": "2026-01-15",
                  "vendor": "株式会社ABC"
                },
                "subcategory": "交通費",
                "suggestedAccount": "6200"
              }
            },
            "type": "object"
          },
          "status": {
            "description": "Document status",
            "enum": [
              "draft",
              "published",
              "archived"
            ],
            "example": "published",
            "type": "string"
          }
        },
        "type": "object"
      },
      "UpdateDocumentStatusRequest": {
        "properties": {
          "document_id": {
            "description": "Generated document ID",
            "example": "doc_123456",
            "type": "string"
          },
          "document_type": {
            "description": "Type of document",
            "example": "articles_of_incorporation",
            "type": "string"
          },
          "error_message": {
            "description": "Error message if applicable",
            "example": "Template processing failed",
            "type": "string"
          },
          "status": {
            "$ref": "#/components/schemas/DocumentGenerationStatus"
          }
        },
        "required": [
          "document_type",
          "status"
        ],
        "type": "object"
      },
      "UpdateDocumentTemplateBody": {
        "properties": {
          "description": {
            "type": "string"
          },
          "name": {
            "type": "string"
          },
          "template_json": {
            "description": "Field layout JSON matching src/common/templates/*.json conventions",
            "type": "object"
          }
        },
        "type": "object"
      },
      "UpdateDocumentViewerConfigResponse": {
        "properties": {
          "data": {
            "example": "Document viewer config updated successfully",
            "type": "string"
          },
          "message": {
            "example": "Document viewer config updated successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "UpdateEmployeeInput": {
        "description": "Same fields as CreateEmployeeInput, all optional",
        "type": "object"
      },
      "UpdateExpenseRequest": {
        "properties": {
          "amount": {
            "description": "Expense amount",
            "example": 5000,
            "minimum": 0,
            "type": "number"
          },
          "business_purpose": {
            "description": "Business purpose of the expense",
            "example": "Client meeting to discuss project requirements",
            "type": "string"
          },
          "category": {
            "description": "Expense category for Japanese tax compliance",
            "enum": [
              0,
              1,
              2,
              3,
              4,
              5,
              6,
              7,
              8,
              9,
              10,
              11,
              12,
              13,
              14,
              15,
              16,
              17,
              18,
              19,
              20,
              21,
              22,
              23,
              24,
              25,
              26
            ],
            "type": "integer"
          },
          "currency": {
            "description": "Currency code (ISO 4217)",
            "example": "JPY",
            "type": "string"
          },
          "expense_date": {
            "description": "Expense date as Unix timestamp",
            "example": 1640995200,
            "type": "integer"
          },
          "payee": {
            "description": "Payee or vendor name",
            "example": "ABC Restaurant",
            "type": "string"
          },
          "payment_method": {
            "description": "Payment method used",
            "enum": [
              0,
              1,
              2,
              3,
              4,
              5,
              6,
              7,
              8,
              9,
              10,
              11
            ],
            "type": "integer"
          },
          "remarks": {
            "description": "Additional remarks and notes",
            "example": [
              "Receipt attached",
              "Business purpose documented"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "tax_type": {
            "description": "Japanese tax type classification",
            "enum": [
              1,
              2,
              3,
              4,
              5
            ],
            "type": "integer"
          }
        },
        "type": "object"
      },
      "UpdateFileGroupRequest": {
        "properties": {
          "description": {
            "maxLength": 1000,
            "type": "string"
          },
          "document_id": {
            "description": "Set or change the target document",
            "format": "uuid",
            "type": "string"
          },
          "label": {
            "maxLength": 255,
            "type": "string"
          },
          "status": {
            "description": "Only pending/archived allowed via PATCH. Use /confirm endpoint to confirm.",
            "enum": [
              "pending",
              "archived"
            ],
            "type": "string"
          },
          "target_document_type": {
            "type": "string"
          },
          "total_amount": {
            "minimum": 0,
            "type": "integer"
          }
        },
        "type": "object"
      },
      "UpdateFixedAssetRequest": {
        "properties": {
          "acquisition_cost": {
            "description": "Original acquisition cost in Japanese Yen",
            "example": 155000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "acquisition_date": {
            "description": "Asset acquisition date in YYYYMMDD format",
            "example": 20240115,
            "maximum": 99991231,
            "minimum": 19000101,
            "type": "integer"
          },
          "classification": {
            "$ref": "#/components/schemas/AssetClassification",
            "description": "Asset classification according to Japanese tax law"
          },
          "closing_book_value": {
            "description": "Book value at end of period",
            "example": 124000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "depreciation_method": {
            "$ref": "#/components/schemas/DepreciationMethod",
            "description": "Depreciation calculation method"
          },
          "in_service_date": {
            "description": "事業供用日 (YYYYMMDD). Changing it regenerates the projected depreciation schedule; booked years are kept. Send null or an empty string to clear it (depreciation then starts from acquisition_date).",
            "example": 20240201,
            "nullable": true,
            "type": "integer"
          },
          "location": {
            "description": "Physical location of the asset",
            "example": "本社 2階 総務部",
            "maxLength": 255,
            "type": "string"
          },
          "name": {
            "description": "Asset name or description",
            "example": "デスクトップコンピュータ Dell OptiPlex 7090 (更新済み)",
            "maxLength": 255,
            "type": "string"
          },
          "opening_book_value": {
            "description": "Book value at beginning of period",
            "example": 155000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "quantity": {
            "description": "Number of asset units",
            "example": 1,
            "minimum": 1,
            "type": "integer"
          },
          "remarks": {
            "description": "Additional notes or remarks",
            "example": "保証期間延長: 2028年1月まで",
            "maxLength": 255,
            "type": "string"
          },
          "shokyaku_tenant_fixture": {
            "description": "償却資産申告の対象（テナント造作）. true = a 建物 (a tenant 内装・造作 on a leased building) goes on the 償却資産申告; false = never; null = SBC default (a 建物 whose location names 「賃借」 is included, flagged as assumed).",
            "example": true,
            "nullable": true,
            "type": "boolean"
          },
          "unit": {
            "description": "Unit of measurement",
            "example": "台",
            "type": "string"
          },
          "useful_life": {
            "description": "Useful life in years for depreciation",
            "example": 4,
            "minimum": 1,
            "type": "integer"
          }
        },
        "type": "object"
      },
      "UpdateFolderRequest": {
        "properties": {
          "color": {
            "description": "Folder color",
            "example": "#10B981",
            "type": "string"
          },
          "description": {
            "description": "Folder description",
            "example": "Updated description for financial documents",
            "type": "string"
          },
          "icon": {
            "description": "Folder icon identifier",
            "example": "folder-finance",
            "type": "string"
          },
          "name": {
            "description": "Folder name",
            "example": "Updated Financial Documents",
            "type": "string"
          }
        },
        "type": "object"
      },
      "UpdateInkanRequest": {
        "properties": {
          "description": {
            "description": "Updated description for the inkan",
            "example": "Updated company seal description",
            "maxLength": 500,
            "type": "string"
          }
        },
        "type": "object"
      },
      "UpdateJournalContextPresetsRequest": {
        "properties": {
          "journalContextPresets": {
            "description": "Array of journal context presets (max 10)",
            "items": {
              "$ref": "#/components/schemas/JournalContextPreset"
            },
            "maxItems": 10,
            "type": "array"
          }
        },
        "required": [
          "journalContextPresets"
        ],
        "type": "object"
      },
      "UpdateJournalTemplateRequest": {
        "properties": {
          "credit_account_id": {
            "description": "Credit account ID",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "debit_account_id": {
            "description": "Debit account ID",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "default_amount": {
            "description": "Default amount",
            "example": 1000,
            "type": "number"
          },
          "default_description": {
            "description": "Default journal entry description",
            "example": "交通費",
            "type": "string"
          },
          "description": {
            "description": "Template description",
            "example": "電車・バス・タクシーなどの交通費",
            "type": "string"
          },
          "is_active": {
            "description": "Whether template is active",
            "example": true,
            "type": "boolean"
          },
          "name": {
            "description": "Template name",
            "example": "交通費精算",
            "maxLength": 100,
            "type": "string"
          },
          "shortcut_key": {
            "description": "Shortcut key (F1-F5)",
            "example": "F1",
            "maxLength": 10,
            "type": "string"
          },
          "tax_included": {
            "description": "Whether tax is included in amount",
            "example": false,
            "type": "boolean"
          },
          "tax_rate": {
            "$ref": "#/components/schemas/TaxRate"
          }
        },
        "type": "object"
      },
      "UpdatePaySlipRequest": {
        "properties": {
          "employee_department": {
            "description": "Employee department",
            "example": "営業部",
            "maxLength": 255,
            "type": "string"
          },
          "employee_name": {
            "description": "Employee name",
            "example": "田中太郎",
            "maxLength": 255,
            "type": "string"
          },
          "gross_salary": {
            "description": "Gross salary amount in JPY",
            "example": 350000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "items": {
            "description": "Pay slip items (earnings and deductions)",
            "items": {
              "$ref": "#/components/schemas/CreatePaySlipItemRequest"
            },
            "maxItems": 50,
            "minItems": 1,
            "type": "array"
          },
          "net_pay": {
            "description": "Net pay amount in JPY",
            "example": 265000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "pay_period_end": {
            "description": "Pay period end date in YYYYMMDD format",
            "example": 20240131,
            "maximum": 99991231,
            "minimum": 19700101,
            "type": "integer"
          },
          "pay_period_start": {
            "description": "Pay period start date in YYYYMMDD format",
            "example": 20240101,
            "maximum": 99991231,
            "minimum": 19700101,
            "type": "integer"
          },
          "payment_date": {
            "description": "Payment date in YYYYMMDD format",
            "example": 20240225,
            "maximum": 99991231,
            "minimum": 19700101,
            "type": "integer"
          },
          "payment_type": {
            "$ref": "#/components/schemas/PaymentType",
            "description": "支払種別 (Payment Type)"
          },
          "provision_note": {
            "description": "Additional provision notes",
            "example": "Overtime pay included for January",
            "maxLength": 1000,
            "type": "string"
          },
          "status": {
            "$ref": "#/components/schemas/PaySlipStatus"
          },
          "total_deductions": {
            "description": "Total deductions amount in JPY",
            "example": 85000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "ytd_gross": {
            "description": "Year-to-date gross amount in JPY",
            "example": 1050000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "ytd_income_tax": {
            "description": "Year-to-date income tax amount in JPY",
            "example": 85000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "ytd_social_ins": {
            "description": "Year-to-date social insurance amount in JPY",
            "example": 150000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "ytd_taxable": {
            "description": "Year-to-date taxable amount in JPY",
            "example": 1000000,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          }
        },
        "type": "object"
      },
      "UpdateProcessingStatusRequest": {
        "description": "Request body for updating processing status",
        "properties": {
          "processing_status": {
            "description": "New processing status or null to clear",
            "example": "no_doc_required",
            "oneOf": [
              {
                "$ref": "#/components/schemas/ProcessingStatusEnum"
              },
              {
                "description": "Set to null to clear explicit status and revert to derived behavior",
                "type": "null"
              }
            ]
          }
        },
        "required": [
          "processing_status"
        ],
        "type": "object"
      },
      "UpdateProcessingStatusResponse": {
        "description": "Response after updating processing status",
        "properties": {
          "data": {
            "properties": {
              "derivedStatus": {
                "$ref": "#/components/schemas/ProcessingStatusEnum",
                "description": "What the status would be if derived from journal/document relationships",
                "example": "unprocessed"
              },
              "documentCount": {
                "description": "Number of linked documents",
                "example": 0,
                "type": "integer"
              },
              "effectiveStatus": {
                "$ref": "#/components/schemas/ProcessingStatusEnum",
                "description": "The status that will be displayed (explicit if set, otherwise derived)",
                "example": "no_doc_required"
              },
              "hasJournal": {
                "description": "Whether transaction has a journal entry",
                "example": false,
                "type": "boolean"
              },
              "isExplicit": {
                "description": "Whether status is explicitly set (true) or derived (false)",
                "example": true,
                "type": "boolean"
              },
              "processingStatus": {
                "description": "The stored explicit status (null if cleared)",
                "example": "no_doc_required",
                "oneOf": [
                  {
                    "$ref": "#/components/schemas/ProcessingStatusEnum"
                  },
                  {
                    "type": "null"
                  }
                ]
              },
              "transactionId": {
                "description": "Bank transaction ID",
                "example": "123e4567-e89b-12d3-a456-426614174000",
                "format": "uuid",
                "type": "string"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Processing status updated successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "type": "object"
      },
      "UpdateProfessionalEngagementRequest": {
        "description": "Partial update. Send at least one field (an empty body is a 400).",
        "minProperties": 1,
        "properties": {
          "contact_note": {
            "maxLength": 500,
            "nullable": true,
            "type": "string"
          },
          "display_name": {
            "maxLength": 150,
            "minLength": 1,
            "type": "string"
          },
          "engagement_how": {
            "maxLength": 4000,
            "nullable": true,
            "type": "string"
          },
          "engagement_what": {
            "maxLength": 4000,
            "nullable": true,
            "type": "string"
          },
          "engagement_when": {
            "maxLength": 4000,
            "nullable": true,
            "type": "string"
          },
          "engagement_where": {
            "maxLength": 4000,
            "nullable": true,
            "type": "string"
          },
          "engagement_who": {
            "maxLength": 4000,
            "nullable": true,
            "type": "string"
          },
          "engagement_why": {
            "maxLength": 4000,
            "nullable": true,
            "type": "string"
          },
          "fiscal_year": {
            "maximum": 2100,
            "minimum": 2000,
            "nullable": true,
            "type": "integer"
          },
          "notes": {
            "maxLength": 4000,
            "nullable": true,
            "type": "string"
          },
          "office_name": {
            "maxLength": 150,
            "nullable": true,
            "type": "string"
          },
          "professional_type": {
            "enum": [
              "TAX_ACCOUNTANT",
              "AUDITOR",
              "LAWYER",
              "JUDICIAL_SCRIVENER",
              "SOCIAL_INSURANCE",
              "OTHER"
            ],
            "type": "string"
          },
          "status": {
            "enum": [
              "considering",
              "requested",
              "engaged",
              "completed",
              "declined"
            ],
            "type": "string"
          }
        },
        "type": "object"
      },
      "UpdateRemarkRequest": {
        "properties": {
          "is_active": {
            "description": "Whether remark is active",
            "example": true,
            "type": "boolean"
          },
          "linked_account_id": {
            "description": "Linked account ID for categorization",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "linked_category": {
            "description": "Linked expense category",
            "example": 3,
            "type": "integer"
          },
          "reading": {
            "description": "Reading (フリガナ) for Japanese text",
            "example": "でんしゃだい",
            "type": "string"
          },
          "remark_text": {
            "description": "Remark text for journal entries",
            "example": "電車代（東京駅→大阪駅）",
            "type": "string"
          }
        },
        "type": "object"
      },
      "UpdateReminderConfigRequest": {
        "properties": {
          "consumption_tax_active": {
            "description": "Whether consumption tax reminders are active",
            "example": true,
            "type": "boolean"
          },
          "consumption_tax_day": {
            "description": "Day for consumption tax reminders",
            "example": 17,
            "maximum": 31,
            "minimum": 1,
            "type": "integer"
          },
          "consumption_tax_month": {
            "description": "Month for consumption tax reminders",
            "example": 4,
            "maximum": 12,
            "minimum": 1,
            "type": "integer"
          },
          "corporate_tax_active": {
            "description": "Whether corporate tax reminders are active",
            "example": true,
            "type": "boolean"
          },
          "corporate_tax_day": {
            "description": "Day of month for corporate tax reminders",
            "example": 17,
            "maximum": 31,
            "minimum": 1,
            "type": "integer"
          },
          "corporate_tax_month": {
            "description": "Month for corporate tax reminders",
            "example": 4,
            "maximum": 12,
            "minimum": 1,
            "type": "integer"
          },
          "depreciable_assets_active": {
            "description": "Whether 償却資産申告 reminders are active",
            "example": true,
            "type": "boolean"
          },
          "depreciable_assets_day": {
            "description": "Day for 償却資産申告 submission (recommended: 31)",
            "example": 31,
            "maximum": 31,
            "minimum": 1,
            "type": "integer"
          },
          "depreciable_assets_month": {
            "description": "Month for 償却資産申告 submission (recommended: 1)",
            "example": 1,
            "maximum": 12,
            "minimum": 1,
            "type": "integer"
          },
          "expense_payment_active": {
            "description": "Whether expense payment reminders are active",
            "example": true,
            "type": "boolean"
          },
          "expense_payment_day": {
            "description": "Day of month for expense payment reminders",
            "example": 30,
            "maximum": 31,
            "minimum": 1,
            "type": "integer"
          },
          "final_tax_return_active": {
            "description": "Whether 確定申告 reminders are active",
            "example": false,
            "type": "boolean"
          },
          "final_tax_return_day": {
            "description": "Day for 確定申告 submission (recommended: 15)",
            "example": 15,
            "maximum": 31,
            "minimum": 1,
            "type": "integer"
          },
          "final_tax_return_month": {
            "description": "Month for 確定申告 submission (recommended: 3/March)",
            "example": 3,
            "maximum": 12,
            "minimum": 1,
            "type": "integer"
          },
          "invoice_active": {
            "description": "Whether invoice reminders are active",
            "example": true,
            "type": "boolean"
          },
          "invoice_day": {
            "description": "Day of month for invoice reminders",
            "example": 25,
            "maximum": 31,
            "minimum": 1,
            "type": "integer"
          },
          "labor_insurance_active": {
            "description": "Whether labor insurance reminders are active",
            "example": true,
            "type": "boolean"
          },
          "labor_insurance_day": {
            "description": "Day for labor insurance reminders",
            "example": 10,
            "maximum": 31,
            "minimum": 1,
            "type": "integer"
          },
          "labor_insurance_month": {
            "description": "Month for labor insurance reminders",
            "example": 7,
            "maximum": 12,
            "minimum": 1,
            "type": "integer"
          },
          "legal_records_summary_active": {
            "description": "Whether 法定調書合計表 reminders are active",
            "example": true,
            "type": "boolean"
          },
          "legal_records_summary_day": {
            "description": "Day for 法定調書合計表 submission (recommended: 31)",
            "example": 31,
            "maximum": 31,
            "minimum": 1,
            "type": "integer"
          },
          "legal_records_summary_month": {
            "description": "Month for 法定調書合計表 submission (recommended: 1)",
            "example": 1,
            "maximum": 12,
            "minimum": 1,
            "type": "integer"
          },
          "reimbursement_active": {
            "description": "Whether reimbursement reminders are active",
            "example": true,
            "type": "boolean"
          },
          "reimbursement_day": {
            "description": "Day of month for reimbursement reminders",
            "example": 25,
            "maximum": 31,
            "minimum": 1,
            "type": "integer"
          },
          "salary_payment_report_active": {
            "description": "Whether 給与支払報告書 reminders are active",
            "example": true,
            "type": "boolean"
          },
          "salary_payment_report_day": {
            "description": "Day for 給与支払報告書 submission (recommended: 31)",
            "example": 31,
            "maximum": 31,
            "minimum": 1,
            "type": "integer"
          },
          "salary_payment_report_month": {
            "description": "Month for 給与支払報告書 submission (recommended: 1)",
            "example": 1,
            "maximum": 12,
            "minimum": 1,
            "type": "integer"
          },
          "social_insurance_active": {
            "description": "Whether social insurance reminders are active",
            "example": true,
            "type": "boolean"
          },
          "social_insurance_day": {
            "description": "Day for social insurance reminders",
            "example": 10,
            "maximum": 31,
            "minimum": 1,
            "type": "integer"
          },
          "social_insurance_month": {
            "description": "Month for social insurance reminders",
            "example": 7,
            "maximum": 12,
            "minimum": 1,
            "type": "integer"
          },
          "withholding_tax_slip_active": {
            "description": "Whether 源泉徴収票 reminders are active",
            "example": true,
            "type": "boolean"
          },
          "withholding_tax_slip_day": {
            "description": "Day for 源泉徴収票 submission (recommended: 31)",
            "example": 31,
            "maximum": 31,
            "minimum": 1,
            "type": "integer"
          },
          "withholding_tax_slip_month": {
            "description": "Month for 源泉徴収票 submission (recommended: 1)",
            "example": 1,
            "maximum": 12,
            "minimum": 1,
            "type": "integer"
          },
          "year_end_adjustment_active": {
            "description": "Whether year-end adjustment reminders are active",
            "example": true,
            "type": "boolean"
          },
          "year_end_adjustment_day": {
            "description": "Day for year-end adjustment reminders",
            "example": 31,
            "maximum": 31,
            "minimum": 1,
            "type": "integer"
          },
          "year_end_adjustment_month": {
            "description": "Month for year-end adjustment reminders",
            "example": 1,
            "maximum": 12,
            "minimum": 1,
            "type": "integer"
          }
        },
        "type": "object"
      },
      "UpdateSalesInvoiceRequest": {
        "properties": {
          "client_id": {
            "description": "Client identifier",
            "format": "uuid",
            "type": "string"
          },
          "due_date": {
            "description": "Due date as Unix timestamp",
            "example": 1643673600,
            "type": "integer"
          },
          "invoice_number": {
            "description": "Invoice number",
            "example": "INV-2024-001",
            "type": "string"
          },
          "issue_date": {
            "description": "Issue date as Unix timestamp",
            "example": 1640995200,
            "type": "integer"
          },
          "items": {
            "description": "Invoice line items",
            "items": {
              "$ref": "#/components/schemas/InvoiceItem"
            },
            "type": "array"
          },
          "notes": {
            "description": "Additional notes",
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "order_number": {
            "description": "Related order number",
            "example": "ORD-2024-001",
            "type": "string"
          },
          "payment_info": {
            "additionalProperties": true,
            "description": "Payment information",
            "type": "object"
          },
          "period_end": {
            "description": "Project period end as Unix timestamp",
            "example": 1643673600,
            "type": "integer"
          },
          "period_start": {
            "description": "Project period start as Unix timestamp",
            "example": 1640995200,
            "type": "integer"
          },
          "project_title": {
            "description": "Project title or description",
            "example": "E-commerce Website Development",
            "type": "string"
          },
          "quote_number": {
            "description": "Related quote number",
            "example": "QUO-2024-001",
            "type": "string"
          },
          "subtotal": {
            "description": "Subtotal amount before tax",
            "example": 200000,
            "minimum": 0,
            "type": "number"
          },
          "tax": {
            "description": "Tax amount",
            "example": 20000,
            "minimum": 0,
            "type": "number"
          },
          "total": {
            "description": "Total amount including tax",
            "example": 220000,
            "minimum": 0,
            "type": "number"
          }
        },
        "type": "object"
      },
      "UpdateSessionRequest": {
        "properties": {
          "description": {
            "description": "Updated description",
            "type": "string"
          },
          "financialData": {
            "description": "Updated financial data state",
            "type": "object"
          },
          "fiscalYear": {
            "description": "Updated fiscal year",
            "type": "string"
          },
          "name": {
            "description": "Updated session name",
            "type": "string"
          },
          "version": {
            "description": "Current version for optimistic locking",
            "example": 1,
            "type": "integer"
          }
        },
        "required": [
          "financialData",
          "version"
        ],
        "type": "object"
      },
      "UpdateUiPreferencesRequest": {
        "description": "PATCH body for UI preferences. All fields optional; backend shallow-merges. To clear a single table layout, send `{ table_layouts: { [tableId]: null } }`.",
        "properties": {
          "amount_format": {
            "enum": [
              "compact",
              "full"
            ],
            "type": "string"
          },
          "color_scheme": {
            "enum": [
              "system",
              "light",
              "dark"
            ],
            "type": "string"
          },
          "currency_symbol": {
            "enum": [
              "¥",
              "JPY",
              "円"
            ],
            "type": "string"
          },
          "date_format": {
            "enum": [
              "iso",
              "jp-wareki",
              "jp-seireki"
            ],
            "type": "string"
          },
          "density": {
            "enum": [
              "default",
              "comfortable",
              "compact",
              "ja-compact",
              "ultra"
            ],
            "type": "string"
          },
          "dock_hidden": {
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "dock_pin": {
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "font_scale": {
            "maximum": 1.4,
            "minimum": 0.85,
            "type": "number"
          },
          "haptics": {
            "properties": {
              "enabled": {
                "type": "boolean"
              },
              "intensity": {
                "enum": [
                  "light",
                  "medium",
                  "heavy"
                ],
                "type": "string"
              }
            },
            "type": "object"
          },
          "home_feed_order": {
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "home_shortcuts": {
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "large_text": {
            "enum": [
              1,
              1.15,
              1.3
            ],
            "type": "number"
          },
          "quick_actions_mobile": {
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "reduced_motion": {
            "type": "boolean"
          },
          "share_link_expiry_days": {
            "maximum": 3650,
            "minimum": 1,
            "nullable": true,
            "type": "integer"
          },
          "swipe_actions": {
            "additionalProperties": {
              "oneOf": [
                {
                  "properties": {
                    "left": {
                      "type": "string"
                    },
                    "right": {
                      "type": "string"
                    }
                  },
                  "type": "object"
                },
                {
                  "type": "null"
                }
              ]
            },
            "type": "object"
          },
          "table_layouts": {
            "additionalProperties": {
              "oneOf": [
                {
                  "enum": [
                    "cards",
                    "priority",
                    "scroll-frozen"
                  ],
                  "type": "string"
                },
                {
                  "type": "null"
                }
              ]
            },
            "type": "object"
          },
          "table_pinned_columns": {
            "additionalProperties": {
              "oneOf": [
                {
                  "items": {
                    "type": "string"
                  },
                  "type": "array"
                },
                {
                  "type": "null"
                }
              ]
            },
            "type": "object"
          }
        },
        "type": "object"
      },
      "UpdateUserPreferencesRequest": {
        "description": "User preferences update request with optional nested configurations including tour completion tracking",
        "properties": {
          "documentViewerConfig": {
            "$ref": "#/components/schemas/DocumentViewerConfig",
            "description": "Document viewer configuration to update (optional)"
          },
          "preferences": {
            "$ref": "#/components/schemas/UserPreferences",
            "description": "AI provider preferences to update (optional)"
          },
          "tour_completion": {
            "$ref": "#/components/schemas/TourCompletion",
            "description": "Tour completion status to update (optional)"
          }
        },
        "type": "object"
      },
      "UpdateViolationRequest": {
        "properties": {
          "ignoredReason": {
            "description": "Reason for ignoring violation (required when status is ignored)",
            "example": "システム移行時の一時的な重複のため、無視します",
            "minLength": 5,
            "type": "string"
          },
          "resolutionNotes": {
            "description": "Notes about violation resolution",
            "example": "重複取引を削除し、正しい取引のみを残しました",
            "type": "string"
          },
          "status": {
            "$ref": "#/components/schemas/ViolationStatus"
          }
        },
        "required": [
          "status"
        ],
        "type": "object"
      },
      "UpdateWithholdingTaxRequest": {
        "description": "All fields are optional. Only provided fields will be updated.",
        "properties": {
          "category": {
            "$ref": "#/components/schemas/WithholdingCategory"
          },
          "gross_amount": {
            "description": "Gross payment amount in JPY (will recalculate withholding)",
            "example": 500000,
            "minimum": 0,
            "type": "number"
          },
          "payee_address": {
            "description": "Payee address",
            "example": "東京都渋谷区1-1-1",
            "nullable": true,
            "type": "string"
          },
          "payee_my_number": {
            "description": "Payee My Number (マイナンバー)",
            "nullable": true,
            "type": "string"
          },
          "payee_name": {
            "description": "Name of the payee",
            "example": "田中太郎",
            "minLength": 1,
            "type": "string"
          },
          "payee_type": {
            "$ref": "#/components/schemas/PayeeType"
          },
          "payment_date": {
            "description": "Payment date in YYYYMMDD format",
            "example": 20240315,
            "type": "integer"
          },
          "withholding_rate": {
            "description": "Optional custom withholding rate (decimal)",
            "example": 0.1021,
            "maximum": 1,
            "minimum": 0,
            "nullable": true,
            "type": "number"
          }
        },
        "type": "object"
      },
      "UploadBuyerAttachmentRequest": {
        "description": "Request body for uploading a buyer attachment",
        "properties": {
          "attachmentType": {
            "description": "Type of buyer attachment (発注書 = purchase_order, 納品書 = delivery_note)",
            "enum": [
              "purchase_order",
              "delivery_note",
              "other"
            ],
            "example": "purchase_order",
            "type": "string"
          },
          "description": {
            "description": "Optional description of the attachment",
            "example": "ABC株式会社からの発注書",
            "type": "string"
          },
          "fileUploadId": {
            "description": "ID of the previously uploaded file",
            "example": "789e0123-e89b-12d3-a456-426614174002",
            "format": "uuid",
            "type": "string"
          },
          "metadata": {
            "additionalProperties": true,
            "description": "Optional additional metadata",
            "type": "object"
          }
        },
        "required": [
          "fileUploadId",
          "attachmentType"
        ],
        "type": "object"
      },
      "UploadBuyerAttachmentResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/BuyerAttachment"
          },
          "message": {
            "example": "Buyer attachment uploaded successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 201,
            "type": "number"
          }
        },
        "type": "object"
      },
      "UploadInkanRequest": {
        "properties": {
          "description": {
            "description": "Optional description for the inkan",
            "example": "Main company registered seal - 2026 version",
            "maxLength": 500,
            "type": "string"
          },
          "file": {
            "description": "Inkan image file (JPEG, PNG, GIF, WebP, SVG). Max 2MB.",
            "format": "binary",
            "type": "string"
          }
        },
        "required": [
          "file"
        ],
        "type": "object"
      },
      "UpsertJournalContextPresetRequest": {
        "properties": {
          "context": {
            "description": "Context text to be used in AI analysis",
            "example": "この取引は軽井沢別荘の管理運営に関連しています",
            "type": "string"
          },
          "id": {
            "description": "Unique identifier for the preset",
            "example": "preset-1",
            "type": "string"
          },
          "label": {
            "description": "Display label for the preset",
            "example": "不動産管理",
            "type": "string"
          }
        },
        "required": [
          "id",
          "label",
          "context"
        ],
        "type": "object"
      },
      "UsageListResponse": {
        "properties": {
          "data": {
            "properties": {
              "pagination": {
                "properties": {
                  "limit": {
                    "example": 20,
                    "type": "integer"
                  },
                  "page": {
                    "example": 1,
                    "type": "integer"
                  },
                  "total": {
                    "example": 245,
                    "type": "integer"
                  },
                  "total_pages": {
                    "example": 13,
                    "type": "integer"
                  }
                },
                "type": "object"
              },
              "usage_entries": {
                "items": {
                  "$ref": "#/components/schemas/UsageLogEntry"
                },
                "type": "array"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Usage list retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "UsageLogEntry": {
        "properties": {
          "api_key_source": {
            "$ref": "#/components/schemas/ClientUsageApiKeySource",
            "description": "Source of the API key used"
          },
          "completion_tokens": {
            "description": "Number of tokens in the completion/output",
            "example": 75,
            "maximum": 1000000,
            "minimum": 0,
            "type": "integer"
          },
          "cost_estimate": {
            "description": "Estimated cost in USD",
            "example": 0.0045,
            "format": "decimal",
            "maximum": 100,
            "minimum": 0,
            "nullable": true,
            "type": "number"
          },
          "created_at": {
            "description": "Usage record creation timestamp",
            "example": "2024-01-15T10:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "feature": {
            "description": "Product feature dimension (advisor_chat, advisor_rag_retrieval, advisor_rag_rerank, …). Nullable on legacy rows.",
            "example": "advisor_chat",
            "maxLength": 64,
            "nullable": true,
            "type": "string"
          },
          "id": {
            "description": "Usage log entry unique identifier",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "model_used": {
            "description": "AI model used for the operation",
            "example": "gpt-4o",
            "maxLength": 100,
            "type": "string"
          },
          "operation_type": {
            "$ref": "#/components/schemas/ClientUsageOperationType",
            "description": "Type of AI operation performed"
          },
          "processing_time_ms": {
            "description": "Processing time in milliseconds",
            "example": 1250,
            "maximum": 600000,
            "minimum": 0,
            "nullable": true,
            "type": "integer"
          },
          "prompt_tokens": {
            "description": "Number of tokens in the prompt/input",
            "example": 150,
            "maximum": 1000000,
            "minimum": 0,
            "type": "integer"
          },
          "request_metadata": {
            "description": "Additional metadata about the request",
            "example": {
              "document_type": "pdf",
              "file_size_mb": 2.3,
              "page_count": 5
            },
            "nullable": true,
            "type": "object"
          },
          "total_tokens": {
            "description": "Total tokens used (prompt + completion)",
            "example": 225,
            "maximum": 2000000,
            "minimum": 0,
            "type": "integer"
          },
          "user_id": {
            "description": "User identifier",
            "example": "abc12345-def6-7890-ghij-klmnopqrstuv",
            "format": "uuid",
            "type": "string"
          }
        },
        "required": [
          "id",
          "user_id",
          "operation_type",
          "model_used",
          "prompt_tokens",
          "completion_tokens",
          "total_tokens",
          "api_key_source",
          "created_at"
        ],
        "type": "object"
      },
      "UsageStats": {
        "properties": {
          "api_key_source_breakdown": {
            "description": "Usage breakdown by API key source",
            "properties": {
              "SYSTEM_KEY": {
                "properties": {
                  "cost": {
                    "example": 5.45,
                    "type": "number"
                  },
                  "requests": {
                    "example": 12,
                    "type": "integer"
                  },
                  "tokens": {
                    "example": 3750,
                    "type": "integer"
                  }
                },
                "type": "object"
              },
              "USER_KEY": {
                "properties": {
                  "cost": {
                    "example": 18,
                    "type": "number"
                  },
                  "requests": {
                    "example": 30,
                    "type": "integer"
                  },
                  "tokens": {
                    "example": 12000,
                    "type": "integer"
                  }
                },
                "type": "object"
              }
            },
            "type": "object"
          },
          "operation_breakdown": {
            "description": "Usage breakdown by operation type",
            "properties": {
              "IMAGE_ANALYSIS": {
                "properties": {
                  "cost": {
                    "example": 4.8,
                    "type": "number"
                  },
                  "requests": {
                    "example": 8,
                    "type": "integer"
                  },
                  "tokens": {
                    "example": 3200,
                    "type": "integer"
                  }
                },
                "type": "object"
              },
              "PDF_ANALYSIS": {
                "properties": {
                  "cost": {
                    "example": 5.9,
                    "type": "number"
                  },
                  "requests": {
                    "example": 9,
                    "type": "integer"
                  },
                  "tokens": {
                    "example": 4050,
                    "type": "integer"
                  }
                },
                "type": "object"
              },
              "TEXT_GENERATION": {
                "properties": {
                  "cost": {
                    "example": 12.75,
                    "type": "number"
                  },
                  "requests": {
                    "example": 25,
                    "type": "integer"
                  },
                  "tokens": {
                    "example": 8500,
                    "type": "integer"
                  }
                },
                "type": "object"
              }
            },
            "type": "object"
          },
          "total_cost": {
            "description": "Total estimated cost in USD",
            "example": 23.45,
            "format": "decimal",
            "minimum": 0,
            "type": "number"
          },
          "total_requests": {
            "description": "Total number of AI requests made",
            "example": 42,
            "minimum": 0,
            "type": "integer"
          },
          "total_tokens": {
            "description": "Total tokens consumed across all operations",
            "example": 15750,
            "minimum": 0,
            "type": "integer"
          }
        },
        "required": [
          "total_tokens",
          "total_requests",
          "total_cost",
          "operation_breakdown",
          "api_key_source_breakdown"
        ],
        "type": "object"
      },
      "UsageStatsResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/UsageStats"
          },
          "message": {
            "example": "Usage statistics retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "UseCategoryClassificationResponse": {
        "properties": {
          "data": {
            "properties": {
              "summary": {
                "$ref": "#/components/schemas/ApportionmentSummary"
              },
              "updated": {
                "type": "integer"
              }
            },
            "required": [
              "updated",
              "summary"
            ],
            "type": "object"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "UserAchievement": {
        "properties": {
          "achievement_id": {
            "example": "document_creator",
            "type": "string"
          },
          "current_progress": {
            "example": 25,
            "type": "integer"
          },
          "current_tier": {
            "enum": [
              "bronze",
              "silver",
              "gold",
              "platinum"
            ],
            "nullable": true,
            "type": "string"
          },
          "earned_at": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "viewed_at": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          }
        },
        "type": "object"
      },
      "UserActivity": {
        "properties": {
          "action_label": {
            "description": "Japanese display label",
            "example": "給与明細書を編集中",
            "type": "string"
          },
          "action_type": {
            "enum": [
              "document_view",
              "document_edit",
              "document_create",
              "document_delete",
              "document_generate",
              "document_download",
              "document_print",
              "document_send",
              "document_share",
              "document_sign",
              "document_stamp",
              "document_archive",
              "document_restore",
              "document_duplicate",
              "document_update",
              "document_lock",
              "document_unlock",
              "document_void",
              "settings_company",
              "settings_accounting",
              "settings_auth",
              "settings_inkan",
              "settings_signature",
              "settings_profile",
              "settings_notification",
              "settings_payment",
              "settings_integration",
              "settings_export",
              "settings_import",
              "journal_entry",
              "journal_view",
              "journal_delete",
              "journal_approve",
              "journal_reject",
              "bank_reconcile",
              "fiscal_period",
              "account_create",
              "account_edit",
              "account_delete",
              "account_view",
              "trial_balance_view",
              "trial_balance_export",
              "report_view",
              "report_generate",
              "report_export",
              "report_print",
              "report_schedule",
              "client_create",
              "client_edit",
              "client_delete",
              "client_view",
              "ai_chat",
              "ai_suggestion_accept",
              "ai_suggestion_reject",
              "ai_reconcile",
              "ai_analyze",
              "page_visit",
              "session_start",
              "session_end",
              "session_resume",
              "tab_switch",
              "modal_open",
              "modal_close",
              "search_execute",
              "filter_apply",
              "sort_change",
              "form_submit",
              "form_save_draft",
              "form_validation_error",
              "error_occurred",
              "api_error",
              "network_error",
              "login",
              "logout",
              "password_change",
              "mfa_enable",
              "mfa_disable",
              "bulk_upload",
              "bulk_delete",
              "csv_import",
              "csv_export",
              "other"
            ],
            "example": "document_edit",
            "type": "string"
          },
          "batch_id": {
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "browser": {
            "example": "Chrome 120",
            "nullable": true,
            "type": "string"
          },
          "company_id": {
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "created_at": {
            "format": "date-time",
            "type": "string"
          },
          "device_type": {
            "enum": [
              "desktop",
              "tablet",
              "mobile"
            ],
            "nullable": true,
            "type": "string"
          },
          "duration_ms": {
            "example": 5000,
            "nullable": true,
            "type": "integer"
          },
          "entity_id": {
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "entity_name": {
            "example": "2025年1月 給与明細書",
            "nullable": true,
            "type": "string"
          },
          "entity_type": {
            "example": "document",
            "nullable": true,
            "type": "string"
          },
          "error_message": {
            "nullable": true,
            "type": "string"
          },
          "id": {
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "format": "uuid",
            "type": "string"
          },
          "ip_address": {
            "example": "192.168.1.1",
            "nullable": true,
            "type": "string"
          },
          "is_error": {
            "default": false,
            "type": "boolean"
          },
          "metadata": {
            "nullable": true,
            "type": "object"
          },
          "os": {
            "example": "Windows 11",
            "nullable": true,
            "type": "string"
          },
          "referrer": {
            "nullable": true,
            "type": "string"
          },
          "route": {
            "description": "Frontend route path",
            "example": "/documents/abc-123",
            "type": "string"
          },
          "route_params": {
            "example": {
              "documentId": "abc-123",
              "tab": "company-info"
            },
            "nullable": true,
            "type": "object"
          },
          "sequence_number": {
            "nullable": true,
            "type": "integer"
          },
          "session_id": {
            "example": "sess_abc123",
            "nullable": true,
            "type": "string"
          },
          "user_agent": {
            "nullable": true,
            "type": "string"
          }
        },
        "type": "object"
      },
      "UserGoal": {
        "properties": {
          "completed_at": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "current_streak": {
            "nullable": true,
            "type": "integer"
          },
          "goal_id": {
            "example": "setup_company",
            "type": "string"
          },
          "started_at": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "status": {
            "enum": [
              "locked",
              "available",
              "in_progress",
              "completed"
            ],
            "type": "string"
          },
          "total_completions": {
            "example": 5,
            "type": "integer"
          }
        },
        "type": "object"
      },
      "UserPreferences": {
        "description": "AI provider preferences and configuration settings",
        "properties": {
          "claude": {
            "$ref": "#/components/schemas/OpenAIPreferences",
            "description": "Claude (Anthropic) provider configuration and preferences"
          },
          "openai": {
            "$ref": "#/components/schemas/OpenAIPreferences",
            "description": "OpenAI provider configuration and preferences"
          },
          "together": {
            "$ref": "#/components/schemas/OpenAIPreferences",
            "description": "Together AI provider configuration and preferences"
          },
          "tour_completion": {
            "$ref": "#/components/schemas/TourCompletion",
            "description": "Tour/guide completion tracking status"
          }
        },
        "type": "object"
      },
      "UserPreferencesResponse": {
        "properties": {
          "data": {
            "description": "Complete user preferences with masked sensitive data",
            "properties": {
              "documentViewerConfig": {
                "$ref": "#/components/schemas/DocumentViewerConfig",
                "description": "Document viewer configuration and display settings"
              },
              "preferences": {
                "$ref": "#/components/schemas/UserPreferences",
                "description": "AI provider preferences (API keys masked)"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "User preferences retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "UserPreferencesUpdateResponse": {
        "properties": {
          "data": {
            "example": "User preferences updated successfully",
            "type": "string"
          },
          "message": {
            "example": "User preferences updated successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "UserProfileLightResponse": {
        "description": "The real runtime envelope of `GET /api/auth/me/light`: `success` + `message` + camelCase\n`data` (the response case-conversion middleware camelizes `avatar_url` → `avatarUrl`), plus the\npiggybacked `csrfToken`. The previous spec claimed `statusCode` + `avatar_url`, which the route has\nnever sent — corrected here, no runtime change.",
        "properties": {
          "csrfToken": {
            "description": "Double-submit CSRF token — the SAME value as the `sbc_csrf_token` cookie set on this\nresponse. Cache it in memory and send it as `X-CSRF-Token` on state-changing requests instead of calling\n`GET /api/csrf/token`. Treat it as opaque; the server-side format is\n`<random>.<issued-at>.<signature>`. A token this server issued and that has not expired is reused (its\nMax-Age is re-set to its REMAINING life), so a probe from one tab never invalidates another tab's cached\ntoken. A new token is minted when the jar has none, when the value was not issued by this server, or when\nit is older than one hour — so a long-lived session sees at most one rotation per hour.",
            "example": "_kzczlJ6y6rlJ3n8xpak82Hd0a5SJv_bOsrSTFLcDfE.tlqo00.Npzm781CB1awR1_1c5uXhb47dQEnKqWp9NurbZ3Opt0",
            "type": "string"
          },
          "data": {
            "properties": {
              "avatarUrl": {
                "description": "User profile picture URL",
                "example": "https://lh3.googleusercontent.com/a/default-user=s96-c",
                "format": "uri",
                "nullable": true,
                "type": "string"
              },
              "email": {
                "description": "User email address",
                "example": "user@example.com",
                "format": "email",
                "type": "string"
              },
              "id": {
                "description": "Unique user identifier",
                "example": "550e8400-e29b-41d4-a716-446655440000",
                "format": "uuid",
                "type": "string"
              },
              "name": {
                "description": "User display name (display_name or first_name)",
                "example": "John Doe",
                "nullable": true,
                "type": "string"
              }
            },
            "required": [
              "id",
              "email"
            ],
            "type": "object"
          },
          "message": {
            "example": "Success",
            "type": "string"
          },
          "requestId": {
            "nullable": true,
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data",
          "csrfToken"
        ],
        "type": "object"
      },
      "UserProfileResponse": {
        "properties": {
          "data": {
            "properties": {
              "avatar_url": {
                "description": "User profile picture URL",
                "example": "https://lh3.googleusercontent.com/a/default-user=s96-c",
                "format": "uri",
                "nullable": true,
                "type": "string"
              },
              "created_at": {
                "description": "Account creation timestamp",
                "example": "2024-01-15T10:30:00.000Z",
                "format": "date-time",
                "type": "string"
              },
              "email": {
                "description": "User email address",
                "example": "user@example.com",
                "format": "email",
                "type": "string"
              },
              "id": {
                "description": "Unique user identifier",
                "example": "550e8400-e29b-41d4-a716-446655440000",
                "format": "uuid",
                "type": "string"
              },
              "last_sign_in_at": {
                "description": "Last sign-in timestamp",
                "example": "2024-01-15T10:30:00.000Z",
                "format": "date-time",
                "type": "string"
              },
              "name": {
                "description": "User display name",
                "example": "John Doe",
                "nullable": true,
                "type": "string"
              },
              "providers": {
                "description": "Authentication providers used by the user",
                "example": [
                  "google"
                ],
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              "updated_at": {
                "description": "Last profile update timestamp",
                "example": "2024-01-15T10:30:00.000Z",
                "format": "date-time",
                "type": "string"
              }
            },
            "required": [
              "id",
              "email",
              "providers",
              "last_sign_in_at",
              "created_at",
              "updated_at"
            ],
            "type": "object"
          },
          "message": {
            "example": "User profile retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ValidationIssue": {
        "properties": {
          "amount": {
            "description": "Amount involved (if applicable)",
            "example": 125000,
            "format": "decimal",
            "nullable": true,
            "type": "number"
          },
          "code": {
            "description": "Issue code for programmatic handling",
            "example": "UNRECONCILED_BANK_TRANSACTIONS",
            "type": "string"
          },
          "count": {
            "description": "Number of items affected",
            "example": 5,
            "nullable": true,
            "type": "integer"
          },
          "message": {
            "description": "Human-readable issue description",
            "example": "There are 5 unreconciled bank transactions that must be resolved before closing",
            "type": "string"
          },
          "severity": {
            "description": "Issue severity level",
            "enum": [
              "BLOCKER",
              "WARNING",
              "INFO"
            ],
            "example": "BLOCKER",
            "type": "string"
          }
        },
        "required": [
          "code",
          "message",
          "severity"
        ],
        "type": "object"
      },
      "ValidationProblemsResponse": {
        "properties": {
          "limit": {
            "description": "Result limit",
            "example": 50,
            "type": "integer"
          },
          "problems": {
            "description": "List of problematic transactions",
            "items": {
              "$ref": "#/components/schemas/ProblematicTransaction"
            },
            "type": "array"
          },
          "total": {
            "description": "Total problems found",
            "example": 6,
            "type": "integer"
          }
        },
        "required": [
          "problems",
          "total",
          "limit"
        ],
        "type": "object"
      },
      "ValidationResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/EnumValidationResult"
          },
          "message": {
            "example": "有効な値です",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "VapidKeyResponse": {
        "properties": {
          "data": {
            "properties": {
              "publicKey": {
                "description": "VAPID public key for push notification setup",
                "example": "BEl62iUYgUivxIkv69yViEuiBIa-Ib9-SkvMeAtA3LFw",
                "type": "string"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "VAPID public key retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "VerifyBackupEmailRequest": {
        "properties": {
          "token": {
            "description": "Verification token from email",
            "example": "abc123def456...",
            "minLength": 32,
            "type": "string"
          }
        },
        "required": [
          "token"
        ],
        "type": "object"
      },
      "VerifyRecoveryCodeRequest": {
        "properties": {
          "code": {
            "description": "Recovery code in format XXXX-XXXX-XXXX",
            "example": "ABCD-1234-EFGH",
            "pattern": "^[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$",
            "type": "string"
          },
          "email": {
            "description": "Primary or backup email address",
            "format": "email",
            "type": "string"
          }
        },
        "required": [
          "email",
          "code"
        ],
        "type": "object"
      },
      "VersionInfo": {
        "properties": {
          "commits": {
            "description": "Recent commits",
            "items": {
              "$ref": "#/components/schemas/GitCommit"
            },
            "type": "array"
          },
          "currentVersion": {
            "description": "Current version from package.json",
            "example": "1.2.3",
            "type": "string"
          },
          "recommendedBump": {
            "description": "Recommended version bump based on commits",
            "enum": [
              "major",
              "minor",
              "patch"
            ],
            "example": "minor",
            "type": "string"
          },
          "tags": {
            "description": "Git tags",
            "items": {
              "$ref": "#/components/schemas/GitTag"
            },
            "type": "array"
          }
        },
        "required": [
          "currentVersion",
          "commits",
          "recommendedBump",
          "tags"
        ],
        "type": "object"
      },
      "VersionInfoResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/VersionInfo"
          },
          "message": {
            "example": "Version information retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "ViewportTile": {
        "allOf": [
          {
            "$ref": "#/components/schemas/TileRequest"
          },
          {
            "properties": {
              "bounds": {
                "properties": {
                  "ne": {
                    "properties": {
                      "lat": {
                        "example": 35.7,
                        "type": "number"
                      },
                      "lng": {
                        "example": 139.71,
                        "type": "number"
                      }
                    },
                    "type": "object"
                  },
                  "sw": {
                    "properties": {
                      "lat": {
                        "example": 35.68,
                        "type": "number"
                      },
                      "lng": {
                        "example": 139.69,
                        "type": "number"
                      }
                    },
                    "type": "object"
                  }
                },
                "type": "object"
              },
              "cached": {
                "description": "Whether tile is in cache",
                "example": true,
                "type": "boolean"
              },
              "hits": {
                "description": "Number of cache hits for this tile",
                "example": 5,
                "type": "integer"
              }
            },
            "type": "object"
          }
        ]
      },
      "ViewportTilesResponse": {
        "properties": {
          "data": {
            "properties": {
              "bounds": {
                "properties": {
                  "ne": {
                    "properties": {
                      "lat": {
                        "example": 35.73,
                        "type": "number"
                      },
                      "lng": {
                        "example": 139.73,
                        "type": "number"
                      }
                    },
                    "type": "object"
                  },
                  "sw": {
                    "properties": {
                      "lat": {
                        "example": 35.65,
                        "type": "number"
                      },
                      "lng": {
                        "example": 139.65,
                        "type": "number"
                      }
                    },
                    "type": "object"
                  }
                },
                "type": "object"
              },
              "cachedTiles": {
                "description": "Number of cached tiles",
                "example": 2,
                "type": "integer"
              },
              "tiles": {
                "items": {
                  "$ref": "#/components/schemas/ViewportTile"
                },
                "type": "array"
              },
              "totalTiles": {
                "description": "Total number of tiles",
                "example": 4,
                "type": "integer"
              },
              "zoom": {
                "description": "Zoom level",
                "example": 13,
                "type": "integer"
              }
            },
            "type": "object"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      },
      "ViolationSeverity": {
        "description": "Severity level of integrity violation",
        "enum": [
          "error",
          "warning",
          "info"
        ],
        "example": "error",
        "type": "string"
      },
      "ViolationStatus": {
        "description": "Current status of violation resolution",
        "enum": [
          "open",
          "in_progress",
          "resolved",
          "ignored"
        ],
        "example": "open",
        "type": "string"
      },
      "ViolationType": {
        "description": "Type of integrity violation detected",
        "enum": [
          "DUPLICATE_TRANSACTION",
          "AMOUNT_MISMATCH",
          "DATE_MISMATCH",
          "ACCOUNT_MISMATCH",
          "MISSING_LINK",
          "BALANCE_ERROR",
          "COUNT_MISMATCH",
          "MISSING_EVIDENCE",
          "PERIOD_BOUNDARY",
          "TAX_CALCULATION",
          "SUSPENSE_BALANCE",
          "UNPAID_INVOICE"
        ],
        "example": "DUPLICATE_TRANSACTION",
        "type": "string"
      },
      "ViolationUpdateResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/IntegrityViolation"
          },
          "message": {
            "example": "違反状況を更新しました",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "VoidDocumentRequest": {
        "properties": {
          "reason": {
            "description": "Reason for voiding the document (required for audit trail)",
            "example": "入力ミスのため無効化",
            "maxLength": 500,
            "type": "string"
          }
        },
        "required": [
          "reason"
        ],
        "type": "object"
      },
      "VoidDocumentResponse": {
        "properties": {
          "data": {
            "properties": {
              "id": {
                "format": "uuid",
                "type": "string"
              },
              "isVoided": {
                "example": true,
                "type": "boolean"
              },
              "voidReason": {
                "example": "入力ミスのため無効化",
                "type": "string"
              },
              "voidedAt": {
                "format": "date-time",
                "type": "string"
              },
              "voidedBy": {
                "format": "uuid",
                "type": "string"
              }
            },
            "type": "object"
          },
          "message": {
            "example": "Document voided successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "type": "object"
      },
      "WithholdingCategory": {
        "description": "Category of withholding tax payment",
        "enum": [
          "salary",
          "bonus",
          "retirement",
          "freelance_fee",
          "professional_fee",
          "royalty",
          "prize",
          "other"
        ],
        "example": "freelance_fee",
        "type": "string"
      },
      "WithholdingData": {
        "properties": {
          "categories": {
            "description": "Withholding tax categories",
            "items": {
              "$ref": "#/components/schemas/EnumItem"
            },
            "type": "array"
          },
          "payeeTypes": {
            "description": "Payee types",
            "items": {
              "$ref": "#/components/schemas/EnumItem"
            },
            "type": "array"
          }
        },
        "required": [
          "categories",
          "payeeTypes"
        ],
        "type": "object"
      },
      "WithholdingDataResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/WithholdingData"
          },
          "message": {
            "example": "源泉徴収参照データを取得しました",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "WithholdingMonthlySummary": {
        "properties": {
          "byCategory": {
            "description": "Breakdown by withholding category",
            "items": {
              "properties": {
                "category": {
                  "example": "freelance_fee",
                  "type": "string"
                },
                "count": {
                  "example": 5,
                  "type": "integer"
                },
                "grossAmount": {
                  "example": 1500000,
                  "format": "decimal",
                  "type": "number"
                },
                "withholdingAmount": {
                  "example": 153150,
                  "format": "decimal",
                  "type": "number"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "month": {
            "description": "Month of the summary",
            "example": 3,
            "type": "integer"
          },
          "paymentDueDate": {
            "description": "Payment due date for withholding taxes",
            "example": "2024-04-10",
            "type": "string"
          },
          "paymentStatus": {
            "description": "Overall payment status for the month",
            "example": "pending",
            "type": "string"
          },
          "pendingPayments": {
            "description": "Number of pending payments to tax authorities",
            "example": 1,
            "type": "integer"
          },
          "totalGrossAmount": {
            "description": "Total gross payment amount for the month",
            "example": 2500000,
            "format": "decimal",
            "type": "number"
          },
          "totalWithholdingAmount": {
            "description": "Total withholding tax amount for the month",
            "example": 255250,
            "format": "decimal",
            "type": "number"
          },
          "year": {
            "description": "Year of the summary",
            "example": 2024,
            "type": "integer"
          }
        },
        "required": [
          "year",
          "month",
          "totalGrossAmount",
          "totalWithholdingAmount",
          "paymentDueDate",
          "paymentStatus",
          "byCategory",
          "pendingPayments"
        ],
        "type": "object"
      },
      "WithholdingPaymentStatus": {
        "description": "Status of withholding tax payment to authorities",
        "enum": [
          "pending",
          "scheduled",
          "paid",
          "late",
          "cancelled"
        ],
        "example": "pending",
        "type": "string"
      },
      "WithholdingSlipData": {
        "properties": {
          "calculatedTax": {
            "description": "Calculated income tax (算出税額)",
            "example": 211900,
            "format": "decimal",
            "type": "number"
          },
          "deductions": {
            "properties": {
              "basicDeduction": {
                "description": "Basic deduction",
                "example": 480000,
                "format": "decimal",
                "type": "number"
              },
              "dependentDeduction": {
                "description": "Dependent deduction",
                "example": 380000,
                "format": "decimal",
                "type": "number"
              },
              "earthquakeInsurance": {
                "description": "Earthquake insurance deduction",
                "example": 25000,
                "format": "decimal",
                "type": "number"
              },
              "lifeInsurance": {
                "description": "Life insurance deduction",
                "example": 40000,
                "format": "decimal",
                "type": "number"
              },
              "socialInsurance": {
                "description": "Social insurance deduction",
                "example": 720000,
                "format": "decimal",
                "type": "number"
              },
              "spouseDeduction": {
                "description": "Spouse and special spouse deduction combined",
                "example": 380000,
                "format": "decimal",
                "type": "number"
              },
              "total": {
                "description": "Total deductions",
                "example": 2241000,
                "format": "decimal",
                "type": "number"
              }
            },
            "required": [
              "socialInsurance",
              "lifeInsurance",
              "earthquakeInsurance",
              "spouseDeduction",
              "dependentDeduction",
              "basicDeduction",
              "total"
            ],
            "type": "object"
          },
          "employeeId": {
            "description": "employees.id when the pay slips are linked to an employee record; otherwise the first pay slip id (BL-968)",
            "example": "3f2504e0-4f89-41d3-9a0c-0305e82c3301",
            "type": "string"
          },
          "employeeName": {
            "description": "Employee name",
            "example": "田中太郎",
            "type": "string"
          },
          "fiscalYear": {
            "description": "Fiscal year",
            "example": 2024,
            "type": "integer"
          },
          "grossIncome": {
            "description": "Total gross income (支払金額)",
            "example": 6000000,
            "format": "decimal",
            "type": "number"
          },
          "housingLoanDeduction": {
            "description": "Housing loan tax credit (住宅借入金等特別控除)",
            "example": 210000,
            "format": "decimal",
            "type": "number"
          },
          "incomeAfterDeduction": {
            "description": "Income after salary deduction (給与所得控除後の金額)",
            "example": 4360000,
            "format": "decimal",
            "type": "number"
          },
          "netTax": {
            "description": "Net tax after credits (年税額)",
            "example": 1900,
            "format": "decimal",
            "type": "number"
          },
          "remarks": {
            "description": "Additional remarks for the withholding slip",
            "example": [],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "taxableIncome": {
            "description": "Taxable income (課税所得金額)",
            "example": 2119000,
            "format": "decimal",
            "type": "number"
          },
          "withheldTax": {
            "description": "Total withheld tax (源泉徴収税額)",
            "example": 120000,
            "format": "decimal",
            "type": "number"
          }
        },
        "required": [
          "employeeName",
          "fiscalYear",
          "grossIncome",
          "incomeAfterDeduction",
          "deductions",
          "taxableIncome",
          "calculatedTax",
          "withheldTax",
          "housingLoanDeduction",
          "netTax",
          "remarks"
        ],
        "type": "object"
      },
      "WithholdingSlipRequest": {
        "properties": {
          "employee_id": {
            "description": "employees.id of the payee (BL-219). Selects rows by employee rather than by name, so two payees sharing a name are not merged; legacy rows without an employee id are included when their name matches exactly one active employee. Takes precedence over payee_name.",
            "format": "uuid",
            "type": "string"
          },
          "payee_name": {
            "description": "Name of the payee for withholding slip. Required unless employee_id is given.",
            "example": "田中太郎",
            "type": "string"
          },
          "year": {
            "description": "Tax year for the withholding slip",
            "example": 2024,
            "maximum": 2030,
            "minimum": 2020,
            "type": "integer"
          }
        },
        "required": [
          "year"
        ],
        "type": "object"
      },
      "WithholdingSlipResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/WithholdingSlipData"
          },
          "message": {
            "example": "源泉徴収票データを生成しました",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "WithholdingSlipSourceDocuments": {
        "properties": {
          "documentId": {
            "description": "The tax_withholding_slip document ID",
            "format": "uuid",
            "type": "string"
          },
          "fiscalYear": {
            "description": "Fiscal year",
            "example": 2025,
            "type": "integer"
          },
          "payeeName": {
            "description": "Payee name extracted from slip content",
            "example": "代表太郎",
            "type": "string"
          },
          "paymentStatements": {
            "items": {
              "properties": {
                "createdAt": {
                  "format": "date-time",
                  "type": "string"
                },
                "documentName": {
                  "type": "string"
                },
                "documentType": {
                  "type": "string"
                },
                "grossAmount": {
                  "type": "number"
                },
                "id": {
                  "format": "uuid",
                  "type": "string"
                },
                "paymentDate": {
                  "description": "YYYYMMDD",
                  "type": "integer"
                },
                "status": {
                  "type": "string"
                },
                "withholdingAmount": {
                  "type": "number"
                },
                "withholdingTaxId": {
                  "format": "uuid",
                  "type": "string"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "salarySlips": {
            "items": {
              "properties": {
                "createdAt": {
                  "format": "date-time",
                  "type": "string"
                },
                "documentName": {
                  "type": "string"
                },
                "documentType": {
                  "example": "salary_slip",
                  "type": "string"
                },
                "grossAmount": {
                  "nullable": true,
                  "type": "number"
                },
                "id": {
                  "format": "uuid",
                  "type": "string"
                },
                "netAmount": {
                  "nullable": true,
                  "type": "number"
                },
                "paymentDate": {
                  "description": "YYYYMMDD",
                  "nullable": true,
                  "type": "integer"
                },
                "socialInsuranceAmount": {
                  "description": "社会保険料合計 (健康保険・厚生年金・雇用保険・介護保険の合算). Aggregated from deduction line items in salary slip content.",
                  "example": 45000,
                  "type": "integer"
                },
                "status": {
                  "type": "string"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "summary": {
            "properties": {
              "fiscalYear": {
                "type": "integer"
              },
              "payeeName": {
                "type": "string"
              },
              "paymentStatementCount": {
                "type": "integer"
              },
              "recordCount": {
                "type": "integer"
              },
              "salarySlipCount": {
                "type": "integer"
              },
              "totalGrossAmount": {
                "type": "number"
              },
              "totalNetAmount": {
                "type": "number"
              },
              "totalSocialInsurance": {
                "description": "社会保険料合計 (年間合算). Sum of all socialInsuranceAmount values across salary slips. Used to populate 社会保険料等控除額 on the 源泉徴収票 renderer.",
                "example": 540000,
                "type": "integer"
              },
              "totalWithholdingAmount": {
                "type": "number"
              }
            },
            "type": "object"
          },
          "withholdingRecords": {
            "items": {
              "properties": {
                "grossAmount": {
                  "type": "number"
                },
                "id": {
                  "format": "uuid",
                  "type": "string"
                },
                "netAmount": {
                  "type": "number"
                },
                "paySlipId": {
                  "format": "uuid",
                  "nullable": true,
                  "type": "string"
                },
                "paymentCategory": {
                  "type": "string"
                },
                "paymentDate": {
                  "type": "integer"
                },
                "sourceDocumentId": {
                  "format": "uuid",
                  "nullable": true,
                  "type": "string"
                },
                "taxPaymentStatus": {
                  "type": "string"
                },
                "withholdingAmount": {
                  "type": "number"
                }
              },
              "type": "object"
            },
            "type": "array"
          }
        },
        "required": [
          "documentId",
          "salarySlips",
          "paymentStatements",
          "withholdingRecords",
          "summary"
        ],
        "type": "object"
      },
      "WithholdingSummaryResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/WithholdingMonthlySummary"
          },
          "message": {
            "example": "Withholding summary retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "WithholdingTax": {
        "properties": {
          "bankTransactionId": {
            "description": "Linked bank transaction ID (tax office payment)",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "categoryCode": {
            "description": "Tax category code",
            "example": "01",
            "nullable": true,
            "type": "string"
          },
          "createdAt": {
            "format": "date-time",
            "type": "string"
          },
          "description": {
            "description": "Description or notes",
            "nullable": true,
            "type": "string"
          },
          "employeeId": {
            "description": "Related employee record ID",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "expenseId": {
            "description": "Related expense record ID",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "grossAmount": {
            "description": "Gross payment amount in JPY",
            "example": 500000,
            "format": "decimal",
            "type": "number"
          },
          "id": {
            "description": "Withholding tax record unique identifier",
            "format": "uuid",
            "type": "string"
          },
          "journalEntryId": {
            "description": "Related journal entry ID",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "netAmount": {
            "description": "Net payment amount in JPY",
            "example": 448950,
            "format": "decimal",
            "type": "number"
          },
          "paySlipId": {
            "description": "Related pay slip record ID",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "payeeAddress": {
            "description": "Payee address",
            "example": "東京都渋谷区1-1-1",
            "nullable": true,
            "type": "string"
          },
          "payeeMyNumber": {
            "description": "Payee My Number (マイナンバー)",
            "nullable": true,
            "type": "string"
          },
          "payeeName": {
            "description": "Name of the payee",
            "example": "田中太郎",
            "type": "string"
          },
          "payeeType": {
            "$ref": "#/components/schemas/PayeeType"
          },
          "paymentCategory": {
            "$ref": "#/components/schemas/WithholdingCategory"
          },
          "paymentDate": {
            "description": "Payment date in YYYYMMDD format",
            "example": 20240315,
            "type": "integer"
          },
          "paymentReference": {
            "description": "Payment reference number",
            "nullable": true,
            "type": "string"
          },
          "sourceDocumentId": {
            "description": "Source document ID (e.g., salary slip or payment statement)",
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "taxPaymentDate": {
            "description": "Actual tax payment date in YYYYMMDD format",
            "nullable": true,
            "type": "integer"
          },
          "taxPaymentDueDate": {
            "description": "Tax payment due date in YYYYMMDD format",
            "example": 20240410,
            "nullable": true,
            "type": "integer"
          },
          "taxPaymentStatus": {
            "$ref": "#/components/schemas/WithholdingPaymentStatus"
          },
          "updatedAt": {
            "format": "date-time",
            "type": "string"
          },
          "withholdingAmount": {
            "description": "Withholding tax amount in JPY",
            "example": 51050,
            "format": "decimal",
            "type": "number"
          },
          "withholdingRate": {
            "description": "Withholding tax rate (decimal)",
            "example": 0.1021,
            "format": "decimal",
            "type": "number"
          }
        },
        "required": [
          "id",
          "payeeName",
          "payeeType",
          "paymentDate",
          "paymentCategory",
          "grossAmount",
          "withholdingRate",
          "withholdingAmount",
          "netAmount",
          "taxPaymentStatus",
          "createdAt",
          "updatedAt"
        ],
        "type": "object"
      },
      "WithholdingTaxListResponse": {
        "properties": {
          "data": {
            "items": {
              "$ref": "#/components/schemas/WithholdingTax"
            },
            "type": "array"
          },
          "message": {
            "example": "Withholding taxes retrieved successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 200,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "WithholdingTaxResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/WithholdingTax"
          },
          "message": {
            "example": "Withholding tax created successfully",
            "type": "string"
          },
          "statusCode": {
            "example": 201,
            "type": "number"
          }
        },
        "required": [
          "statusCode",
          "message",
          "data"
        ],
        "type": "object"
      },
      "WizardFareLinesRequest": {
        "properties": {
          "date": {
            "example": "2026-08-21",
            "format": "date",
            "type": "string"
          },
          "fare": {
            "description": "One-way IC fare, yen 税込",
            "example": 1782,
            "maximum": 29999,
            "minimum": 1,
            "type": "integer"
          },
          "from": {
            "example": "東京",
            "maxLength": 50,
            "type": "string"
          },
          "operator": {
            "description": "鉄道会社 (the 相手方)",
            "example": "JR東日本",
            "maxLength": 100,
            "type": "string"
          },
          "round_trip": {
            "default": false,
            "description": "Books the return ride as its own line",
            "type": "boolean"
          },
          "to": {
            "example": "長野原草津口",
            "maxLength": 50,
            "type": "string"
          }
        },
        "required": [
          "date",
          "from",
          "to",
          "fare"
        ],
        "type": "object"
      },
      "WizardFareRoute": {
        "description": "One of the owner's past fare sections (newest per station pair)",
        "properties": {
          "fare": {
            "description": "Last one-way IC fare entered, yen 税込",
            "example": 1782,
            "type": "number"
          },
          "from": {
            "example": "東京",
            "type": "string"
          },
          "last_date": {
            "format": "date",
            "nullable": true,
            "type": "string"
          },
          "operator": {
            "example": "JR東日本",
            "nullable": true,
            "type": "string"
          },
          "to": {
            "example": "長野原草津口",
            "type": "string"
          }
        },
        "type": "object"
      },
      "WizardItem": {
        "properties": {
          "analysis_status": {
            "enum": [
              "pending",
              "analyzing",
              "completed",
              "failed",
              "skipped"
            ],
            "type": "string"
          },
          "anomalies": {
            "type": "array"
          },
          "category_confidence": {
            "type": "number"
          },
          "claimed_amount": {
            "description": "What the claim books: the traveller's share of extracted_amount",
            "nullable": true,
            "type": "number"
          },
          "extracted_amount": {
            "nullable": true,
            "type": "number"
          },
          "extracted_date": {
            "format": "date",
            "nullable": true,
            "type": "string"
          },
          "extracted_description": {
            "nullable": true,
            "type": "string"
          },
          "extracted_vendor": {
            "nullable": true,
            "type": "string"
          },
          "fare_from": {
            "description": "Set on a fare line: a fare entered from a route search, with no receipt file",
            "nullable": true,
            "type": "string"
          },
          "fare_to": {
            "nullable": true,
            "type": "string"
          },
          "file_name": {
            "type": "string"
          },
          "file_size": {
            "nullable": true,
            "type": "integer"
          },
          "file_type": {
            "nullable": true,
            "type": "string"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "is_business_relevant": {
            "type": "boolean"
          },
          "is_edited": {
            "type": "boolean"
          },
          "lodging_cap_exception": {
            "description": "The owner's reason for booking above the 出張規程 lodging cap",
            "nullable": true,
            "type": "string"
          },
          "lodging_nights": {
            "description": "Nights a lodging receipt covers (0 = not lodging)",
            "nullable": true,
            "type": "integer"
          },
          "matched_business_objective": {
            "nullable": true,
            "type": "string"
          },
          "party_size": {
            "description": "People the receipt paid for (null = not shared)",
            "nullable": true,
            "type": "integer"
          },
          "payment_method": {
            "enum": [
              "cash",
              "personal_card",
              "corporate_card",
              "bank_transfer"
            ],
            "type": "string"
          },
          "relevance_score": {
            "type": "number"
          },
          "reread": {
            "$ref": "#/components/schemas/WizardItemReread"
          },
          "suggested_category": {
            "type": "integer"
          },
          "tax_amount": {
            "nullable": true,
            "type": "number"
          },
          "tax_type": {
            "nullable": true,
            "type": "integer"
          },
          "usage": {
            "description": "AI tokens the reading used (null when no LLM ran)",
            "nullable": true,
            "properties": {
              "inputTokens": {
                "type": "integer"
              },
              "model": {
                "nullable": true,
                "type": "string"
              },
              "outputTokens": {
                "type": "integer"
              },
              "provider": {
                "nullable": true,
                "type": "string"
              },
              "totalTokens": {
                "type": "integer"
              }
            },
            "type": "object"
          },
          "user_notes": {
            "nullable": true,
            "type": "string"
          }
        },
        "type": "object"
      },
      "WizardItemReread": {
        "description": "A re-read in flight (running), its result waiting to be applied (ready), or why it failed",
        "nullable": true,
        "properties": {
          "finished_at": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "kept_unless_overwritten": {
            "description": "Proposed fields that stay as the owner edited them unless overwrite_edited is set",
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "proposed": {
            "nullable": true,
            "properties": {
              "amount": {
                "nullable": true,
                "type": "number"
              },
              "amount_jpy": {
                "nullable": true,
                "type": "number"
              },
              "amount_needs_review": {
                "type": "boolean"
              },
              "anomaly_count": {
                "type": "integer"
              },
              "category": {
                "nullable": true,
                "type": "integer"
              },
              "currency": {
                "type": "string"
              },
              "date": {
                "format": "date",
                "nullable": true,
                "type": "string"
              },
              "description": {
                "nullable": true,
                "type": "string"
              },
              "exchange_rate": {
                "nullable": true,
                "type": "number"
              },
              "tax_type": {
                "nullable": true,
                "type": "integer"
              },
              "vendor": {
                "nullable": true,
                "type": "string"
              }
            },
            "type": "object"
          },
          "reason": {
            "nullable": true,
            "type": "string"
          },
          "requested_at": {
            "format": "date-time",
            "type": "string"
          },
          "status": {
            "enum": [
              "running",
              "ready",
              "failed"
            ],
            "type": "string"
          }
        },
        "type": "object"
      },
      "WizardSession": {
        "properties": {
          "completed_at": {
            "format": "date-time",
            "nullable": true,
            "type": "string"
          },
          "created_at": {
            "format": "date-time",
            "type": "string"
          },
          "daily_allowance_total": {
            "type": "number"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "lifecycle": {
            "description": "Set on GET /sessions rows only",
            "properties": {
              "analysis_stalled": {
                "description": "`analyzing` with no write for 3 minutes; polling analysis-status restarts it",
                "type": "boolean"
              },
              "can_discard": {
                "description": "DELETE /sessions/{id} is allowed: never completed; `creating` only after 10 minutes without a write (abandoned create)",
                "type": "boolean"
              },
              "counts_toward_limit": {
                "type": "boolean"
              },
              "is_idle": {
                "description": "In progress, no write for 14 days; listed, never counted",
                "type": "boolean"
              },
              "item_progress": {
                "properties": {
                  "completed": {
                    "type": "integer"
                  },
                  "failed": {
                    "type": "integer"
                  },
                  "pending": {
                    "type": "integer"
                  },
                  "total": {
                    "type": "integer"
                  }
                },
                "type": "object"
              },
              "last_activity_at": {
                "format": "date-time",
                "type": "string"
              }
            },
            "type": "object"
          },
          "selected_doc_types": {
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "status": {
            "enum": [
              "draft",
              "analyzing",
              "reviewed",
              "creating",
              "completed",
              "failed",
              "cancelled"
            ],
            "type": "string"
          },
          "total_amount": {
            "type": "number"
          },
          "total_items": {
            "type": "integer"
          },
          "trip_info": {
            "nullable": true,
            "type": "object"
          },
          "trip_type": {
            "enum": [
              "travel",
              "reimbursement",
              "other"
            ],
            "type": "string"
          },
          "updated_at": {
            "format": "date-time",
            "type": "string"
          }
        },
        "type": "object"
      },
      "WizardTripChecklist": {
        "properties": {
          "entries": {
            "items": {
              "properties": {
                "answer": {
                  "nullable": true,
                  "type": "object"
                },
                "blocking": {
                  "description": "UNANALYSED_ITEMS / TRIP_NOT_NAMED: no answer settles it; create refuses (422) until the session is fixed",
                  "type": "boolean"
                },
                "code": {
                  "example": "LODGING",
                  "type": "string"
                },
                "itemIds": {
                  "items": {
                    "format": "uuid",
                    "type": "string"
                  },
                  "type": "array"
                },
                "lateReturn": {
                  "description": "LATE_RETURN only: the stored 帰着 fields",
                  "properties": {
                    "allowanceRatePerDay": {
                      "type": "number"
                    },
                    "arrivalNextDay": {
                      "format": "date",
                      "type": "string"
                    },
                    "countArrivalDay": {
                      "nullable": true,
                      "type": "boolean"
                    },
                    "lastDay": {
                      "format": "date",
                      "type": "string"
                    },
                    "returnTime": {
                      "nullable": true,
                      "type": "string"
                    },
                    "returnedAfterMidnight": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                },
                "legs": {
                  "items": {
                    "properties": {
                      "date": {
                        "format": "date",
                        "nullable": true,
                        "type": "string"
                      },
                      "from": {
                        "type": "string"
                      },
                      "recorded": {
                        "description": "A fare line books the leg on its date (both directions for a round trip)",
                        "type": "boolean"
                      },
                      "roundTrip": {
                        "type": "boolean"
                      },
                      "source": {
                        "enum": [
                          "itinerary",
                          "receipt"
                        ],
                        "type": "string"
                      },
                      "to": {
                        "type": "string"
                      }
                    },
                    "type": "object"
                  },
                  "type": "array"
                },
                "lines": {
                  "items": {
                    "type": "string"
                  },
                  "type": "array"
                },
                "lodging": {
                  "description": "LODGING only: each lodging receipt against the 出張規程 cap. A night over the cap books at the cap unless the owner approved the excess with a reason.",
                  "items": {
                    "properties": {
                      "bookedYen": {
                        "description": "What the claim books",
                        "type": "number"
                      },
                      "capPerNight": {
                        "type": "number"
                      },
                      "capYen": {
                        "description": "capPerNight × nights",
                        "type": "number"
                      },
                      "exceptionReason": {
                        "nullable": true,
                        "type": "string"
                      },
                      "itemId": {
                        "format": "uuid",
                        "type": "string"
                      },
                      "label": {
                        "type": "string"
                      },
                      "nights": {
                        "type": "integer"
                      },
                      "receiptYen": {
                        "description": "The traveller's share of the receipt",
                        "type": "number"
                      }
                    },
                    "type": "object"
                  },
                  "type": "array"
                },
                "question": {
                  "type": "string"
                },
                "resolved": {
                  "type": "boolean"
                },
                "rule": {
                  "type": "string"
                },
                "title": {
                  "example": "宿泊",
                  "type": "string"
                }
              },
              "type": "object"
            },
            "type": "array"
          },
          "unresolvedCount": {
            "type": "integer"
          }
        },
        "type": "object"
      },
      "WorkLog": {
        "properties": {
          "description": {
            "nullable": true,
            "type": "string"
          },
          "evidence_url": {
            "nullable": true,
            "type": "string"
          },
          "hire_id": {
            "format": "uuid",
            "type": "string"
          },
          "hours_worked": {
            "type": "number"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "work_date": {
            "format": "date",
            "type": "string"
          }
        },
        "type": "object"
      },
      "WorkflowDocument": {
        "properties": {
          "client_name": {
            "example": "株式会社テスト",
            "nullable": true,
            "type": "string"
          },
          "created_at": {
            "format": "date-time",
            "type": "string"
          },
          "document_name": {
            "example": "見積書-2026-001",
            "type": "string"
          },
          "document_type": {
            "example": "sales_quotation",
            "type": "string"
          },
          "id": {
            "format": "uuid",
            "type": "string"
          },
          "status": {
            "example": "confirmed",
            "type": "string"
          },
          "total_amount": {
            "example": 550000,
            "nullable": true,
            "type": "integer"
          },
          "updated_at": {
            "format": "date-time",
            "type": "string"
          }
        },
        "type": "object"
      },
      "WorksheetAccount": {
        "description": "One 精算表 row — an account split into 試算表 (pre-adjustment) and 修正記入 (adjustment) figures",
        "properties": {
          "accountCode": {
            "example": "504",
            "type": "string"
          },
          "accountName": {
            "example": "旅費交通費",
            "type": "string"
          },
          "adjustmentCredit": {
            "description": "修正記入 貸方 (JPY)",
            "example": 0,
            "type": "number"
          },
          "adjustmentDebit": {
            "description": "修正記入 借方 (JPY)",
            "example": 0,
            "type": "number"
          },
          "category": {
            "enum": [
              "asset",
              "liability",
              "equity",
              "revenue",
              "expense"
            ],
            "example": "expense",
            "type": "string"
          },
          "trialCredit": {
            "description": "試算表 貸方 (JPY)",
            "example": 0,
            "type": "number"
          },
          "trialDebit": {
            "description": "試算表 借方 (JPY)",
            "example": 152491,
            "type": "number"
          }
        },
        "required": [
          "accountCode",
          "accountName",
          "category",
          "trialDebit",
          "trialCredit",
          "adjustmentDebit",
          "adjustmentCredit"
        ],
        "type": "object"
      },
      "WorksheetResponse": {
        "properties": {
          "data": {
            "properties": {
              "accounts": {
                "items": {
                  "$ref": "#/components/schemas/WorksheetAccount"
                },
                "type": "array"
              },
              "totals": {
                "properties": {
                  "adjustmentCredit": {
                    "example": 50000,
                    "type": "number"
                  },
                  "adjustmentDebit": {
                    "example": 50000,
                    "type": "number"
                  },
                  "trialCredit": {
                    "example": 12345678,
                    "type": "number"
                  },
                  "trialDebit": {
                    "example": 12345678,
                    "type": "number"
                  }
                },
                "required": [
                  "trialDebit",
                  "trialCredit",
                  "adjustmentDebit",
                  "adjustmentCredit"
                ],
                "type": "object"
              }
            },
            "required": [
              "accounts",
              "totals"
            ],
            "type": "object"
          },
          "message": {
            "example": "Worksheet retrieved successfully",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "XPRewardDefinition": {
        "properties": {
          "amount": {
            "example": 20,
            "type": "integer"
          },
          "description": {
            "properties": {
              "en": {
                "example": "Document creation",
                "type": "string"
              },
              "ja": {
                "example": "書類作成",
                "type": "string"
              }
            },
            "type": "object"
          },
          "event": {
            "example": "document_create",
            "type": "string"
          },
          "maxDailyOccurrences": {
            "example": 20,
            "nullable": true,
            "type": "integer"
          }
        },
        "type": "object"
      },
      "YearCloseBlockingQuestion": {
        "properties": {
          "ackable": {
            "description": "false = 確認記録では閉じられない（PREPAID_INPUT_CREDIT 等）。修正か税理士の回答が必要",
            "type": "boolean"
          },
          "domain": {
            "nullable": true,
            "type": "string"
          },
          "engagementId": {
            "format": "uuid",
            "nullable": true,
            "type": "string"
          },
          "latestProfessionalReply": {
            "description": "税理士の最新のやり取り",
            "nullable": true,
            "type": "string"
          },
          "questionKey": {
            "example": "owner:okada-fy2025:01",
            "type": "string"
          },
          "severity": {
            "enum": [
              "blocking",
              "material"
            ],
            "type": "string"
          },
          "sortOrder": {
            "description": "確認事項管理表での No.",
            "nullable": true,
            "type": "integer"
          },
          "status": {
            "enum": [
              "open",
              "answered"
            ],
            "type": "string"
          },
          "title": {
            "type": "string"
          }
        },
        "required": [
          "questionKey",
          "title",
          "severity",
          "status",
          "ackable"
        ],
        "type": "object"
      },
      "YearCloseGate": {
        "properties": {
          "action": {
            "description": "判定した行為（GET は closing = その年度のすべての確認事項）",
            "enum": [
              "closing",
              "corporate_xtx",
              "local_xml",
              "consumption_xtx"
            ],
            "type": "string"
          },
          "blocked": {
            "description": "true の間、決算確定と法人税・消費税 XTX の作成は 409 になる",
            "type": "boolean"
          },
          "blocking": {
            "items": {
              "$ref": "#/components/schemas/YearCloseBlockingQuestion"
            },
            "type": "array"
          },
          "fiscalYear": {
            "example": 2025,
            "type": "integer"
          },
          "integrityRun": {
            "description": "判定に使った整合性チェック（その年度を対象にした実行）。null = 未実行",
            "nullable": true,
            "properties": {
              "completedAt": {
                "format": "date-time",
                "type": "string"
              },
              "periodEnd": {
                "example": 20260215,
                "type": "integer"
              },
              "periodStart": {
                "example": 20250606,
                "type": "integer"
              },
              "stale": {
                "description": "true = 実行後に年度内の仕訳が変わった（再チェック推奨）",
                "type": "boolean"
              }
            },
            "required": [
              "completedAt",
              "periodStart",
              "periodEnd",
              "stale"
            ],
            "type": "object"
          },
          "override": {
            "description": "「税理士に確認済みとして続行」の記録。記録時の確認事項だけを対象にする",
            "nullable": true,
            "properties": {
              "coveredKeys": {
                "items": {
                  "type": "string"
                },
                "type": "array"
              },
              "coversAll": {
                "description": "false = 記録後に増えた確認事項がある",
                "type": "boolean"
              },
              "createdAt": {
                "format": "date-time",
                "type": "string"
              },
              "id": {
                "format": "uuid",
                "type": "string"
              },
              "note": {
                "type": "string"
              }
            },
            "type": "object"
          },
          "settledCount": {
            "description": "税理士の回答・確認・終了で解決した要確認以上の件数",
            "type": "integer"
          }
        },
        "required": [
          "fiscalYear",
          "action",
          "blocked",
          "blocking",
          "settledCount",
          "override",
          "integrityRun"
        ],
        "type": "object"
      },
      "YearEndAdjustmentHealthResponse": {
        "properties": {
          "features": {
            "example": [
              "Aggregate annual income (給与・賞与集計)",
              "Calculate all deductions (各種控除)",
              "Income tax calculation (所得税計算)",
              "Over/under payment calculation (過不足税額)",
              "Withholding slip data (源泉徴収票)"
            ],
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "message": {
            "example": "年末調整 API is running",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "features"
        ],
        "type": "object"
      },
      "YearEndAdjustmentResult": {
        "properties": {
          "calculatedAt": {
            "description": "Calculation timestamp",
            "example": "2024-12-31T15:30:00.000Z",
            "format": "date-time",
            "type": "string"
          },
          "employeeCount": {
            "description": "Number of employees processed",
            "example": 10,
            "type": "integer"
          },
          "employees": {
            "description": "Detailed results for each employee",
            "items": {
              "$ref": "#/components/schemas/EmployeeAnnualIncome"
            },
            "type": "array"
          },
          "fiscalYear": {
            "description": "Fiscal year of the adjustment",
            "example": 2024,
            "type": "integer"
          },
          "summary": {
            "$ref": "#/components/schemas/YearEndAdjustmentSummary"
          }
        },
        "required": [
          "fiscalYear",
          "employeeCount",
          "employees",
          "summary",
          "calculatedAt"
        ],
        "type": "object"
      },
      "YearEndAdjustmentSummary": {
        "properties": {
          "additionalCount": {
            "description": "Number of employees with additional tax collection",
            "example": 2,
            "type": "integer"
          },
          "refundCount": {
            "description": "Number of employees receiving refunds",
            "example": 8,
            "type": "integer"
          },
          "totalAdjustment": {
            "description": "Total adjustment amount (positive for net refund)",
            "example": 300000,
            "format": "decimal",
            "type": "number"
          },
          "totalGrossIncome": {
            "description": "Total gross income for all employees",
            "example": 30000000,
            "format": "decimal",
            "type": "number"
          },
          "totalTax": {
            "description": "Total calculated tax for all employees",
            "example": 1500000,
            "format": "decimal",
            "type": "number"
          },
          "totalWithheld": {
            "description": "Total withheld tax for all employees",
            "example": 1800000,
            "format": "decimal",
            "type": "number"
          }
        },
        "required": [
          "totalGrossIncome",
          "totalTax",
          "totalWithheld",
          "totalAdjustment",
          "refundCount",
          "additionalCount"
        ],
        "type": "object"
      },
      "YearEndCalculationResponse": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/YearEndAdjustmentResult"
          },
          "message": {
            "example": "年末調整を完了しました（10名）",
            "type": "string"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "message",
          "data"
        ],
        "type": "object"
      },
      "YearEndDeductions": {
        "properties": {
          "basicDeduction": {
            "description": "Basic deduction amount (基礎控除)",
            "example": 480000,
            "format": "decimal",
            "type": "number"
          },
          "dependentDeduction": {
            "description": "Dependent deduction amount (扶養控除)",
            "example": 380000,
            "format": "decimal",
            "type": "number"
          },
          "earthquakeInsuranceDeduction": {
            "description": "Earthquake insurance deduction amount (地震保険料控除)",
            "example": 25000,
            "format": "decimal",
            "type": "number"
          },
          "housingLoanDeduction": {
            "description": "Housing loan tax credit amount (住宅借入金等特別控除)",
            "example": 210000,
            "format": "decimal",
            "type": "number"
          },
          "idecoDeduction": {
            "description": "iDeCo contribution deduction amount",
            "example": 276000,
            "format": "decimal",
            "type": "number"
          },
          "lifeInsuranceDeduction": {
            "description": "Life insurance deduction amount (生命保険料控除)",
            "example": 40000,
            "format": "decimal",
            "type": "number"
          },
          "newLifeInsurance": {
            "description": "New life insurance premium amount",
            "example": 80000,
            "format": "decimal",
            "type": "number"
          },
          "nursingInsurance": {
            "description": "Nursing care insurance premium amount",
            "example": 20000,
            "format": "decimal",
            "type": "number"
          },
          "oldLifeInsurance": {
            "description": "Old life insurance premium amount",
            "example": 0,
            "format": "decimal",
            "type": "number"
          },
          "smallBusinessMutualAidDeduction": {
            "description": "Small business mutual aid deduction (小規模企業共済等掛金控除)",
            "example": 120000,
            "format": "decimal",
            "type": "number"
          },
          "socialInsuranceDeduction": {
            "description": "Social insurance deduction amount (社会保険料控除)",
            "example": 720000,
            "format": "decimal",
            "type": "number"
          },
          "spouseDeduction": {
            "description": "Spouse deduction amount (配偶者控除)",
            "example": 380000,
            "format": "decimal",
            "type": "number"
          },
          "spouseSpecialDeduction": {
            "description": "Special spouse deduction amount (配偶者特別控除)",
            "example": 0,
            "format": "decimal",
            "type": "number"
          }
        },
        "required": [
          "basicDeduction",
          "spouseDeduction",
          "spouseSpecialDeduction",
          "dependentDeduction",
          "socialInsuranceDeduction",
          "lifeInsuranceDeduction",
          "newLifeInsurance",
          "oldLifeInsurance",
          "nursingInsurance",
          "earthquakeInsuranceDeduction",
          "housingLoanDeduction",
          "smallBusinessMutualAidDeduction",
          "idecoDeduction"
        ],
        "type": "object"
      },
      "YearEndSummaryResponse": {
        "properties": {
          "data": {
            "properties": {
              "calculatedAt": {
                "example": "2024-12-31T15:30:00.000Z",
                "format": "date-time",
                "type": "string"
              },
              "employeeCount": {
                "example": 10,
                "type": "integer"
              },
              "employees": {
                "items": {
                  "$ref": "#/components/schemas/EmployeeSummary"
                },
                "type": "array"
              },
              "fiscalYear": {
                "example": 2024,
                "type": "integer"
              },
              "summary": {
                "$ref": "#/components/schemas/YearEndAdjustmentSummary"
              }
            },
            "type": "object"
          },
          "success": {
            "example": true,
            "type": "boolean"
          }
        },
        "required": [
          "success",
          "data"
        ],
        "type": "object"
      }
    },
    "securitySchemes": {
      "adminToken": {
        "description": "Admin token for demo management operations",
        "in": "header",
        "name": "x-admin-token",
        "type": "apiKey"
      },
      "bearerAuth": {
        "bearerFormat": "JWT",
        "description": "JWT token authentication. Enter your token in the format: Bearer YOUR_TOKEN",
        "scheme": "bearer",
        "type": "http"
      }
    }
  },
  "info": {
    "contact": {
      "email": "kensaurus@gmail.com",
      "name": "Solo Boss Cloud Support"
    },
    "description": "# 次世代一人社長 Backend API\n\nAI-powered business management API for Japanese solo entrepreneurs (一人社長).\n\n## 📊 API Statistics\n- **Paths**: 876\n- **Operations** (all HTTP verbs): 1016\n- **OpenAPI Version**: 3.2.0\n- **Authentication**: Bearer JWT Token\n\n## 🎯 Core Features\n- 📄 Document Processing & OCR\n- 💰 Expense Management\n- 📊 Financial Reports (BS, PL, TB)\n- 🏢 Fixed Asset Management (償却資産申告)\n- 🤖 AI-powered Reconciliation\n- 📋 Japanese Tax Compliance (e-Tax, eLTAX)\n\n---\n\n### 🔄 Automatic Case Conversion (IMPORTANT!)\n\n        **Frontend developers: Always use `camelCase` for all requests and responses.**\n\n        | Direction | Your Code | Wire Format |\n        |-----------|-----------|-------------|\n        | **Request Body** | `{ \"pageSize\": 20, \"pageNumber\": 1 }` | Auto-converted to snake_case |\n        | **Query Params** | `?pageSize=20&pageNumber=1` | Auto-converted to snake_case |\n        | **Response** | You receive `camelCase` | Auto-converted from snake_case |\n\n        #### ✅ Do This:\n        ```javascript\n        // Request body - use camelCase\n        const response = await api.post('/documents', {\n          documentName: \"Invoice 2024\",\n          isLocked: false,\n          pageSize: 20\n        });\n\n        // Query params - use camelCase\n        const docs = await api.get('/documents?pageSize=20&pageNumber=1&type=sales_invoice');\n\n        // Response - receive camelCase\n        console.log(response.data.createdAt);  // ✅ camelCase\n        console.log(response.data.isLocked);   // ✅ camelCase\n        ```\n\n        #### ❌ Don't Do This:\n        ```javascript\n        // DON'T use snake_case in your frontend code\n        const bad = { document_name: \"Invoice\", is_locked: false }; // ❌\n        ```\n\n        The backend middleware handles all conversions automatically. This follows **Google/Microsoft API Guidelines**.\n\n        ---\n\n        ### 🔐 Bearer Token Authentication\n\n        This API uses Bearer token authentication. After logging in via Google OAuth or Magic Link, you'll receive a JWT token.\n\n        ### Using Bearer Authentication in Swagger:\n\n        1. **Click the \"Authorize\" button** above\n        2. **Enter your JWT token** in the format: `Bearer YOUR_TOKEN` or just `YOUR_TOKEN`\n        3. **Click \"Authorize\"**\n\n        ### Example Authorization Header:\n        ```\n        Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...\n        ```\n        All protected endpoints will require a valid Bearer token in the Authorization header.\n\n        ---\n\n        ### 📋 API Versioning Strategy\n\n        This API follows an **additive-only, no-breaking-changes** policy:\n\n        - **No URL versioning** (`/v1/`, `/v2/`) — all endpoints live at `/api/*`\n        - **New fields** are added without removing existing ones\n        - **Deprecated fields** are marked in documentation with a migration timeline\n        - **Breaking changes** (if ever needed) will be communicated via the [Changelog](/changelog) with 90-day advance notice\n        - **API version** is tracked via the `X-API-Version` response header (matches package.json version)\n\n        This approach follows **GitHub, Stripe, and Slack API guidelines** for backward-compatible evolution.\n\n        ---\n\n        ### ⚠️ Error Response Format (RFC 9457)\n\n        All error responses follow [RFC 9457 Problem Details](https://www.rfc-editor.org/rfc/rfc9457.html):\n\n        ```json\n        {\n          \"type\": \"https://api.soloboss.cloud/errors/ERR_3001\",\n          \"title\": \"Invalid Input\",\n          \"status\": 400,\n          \"detail\": \"入力内容が無効です\",\n          \"instance\": \"/api/journals/123\",\n          \"code\": \"ERR_3001\",\n          \"retryable\": false,\n          \"guidance\": \"入力内容を確認してください\",\n          \"requestId\": \"req_abc123\"\n        }\n        ```\n\n        | Field | Description |\n        |-------|-------------|\n        | `type` | URI reference identifying the error type |\n        | `title` | Short human-readable summary |\n        | `status` | HTTP status code |\n        | `detail` | Detailed explanation (localized) |\n        | `instance` | URI of the specific request that caused the error |\n        | `code` | Machine-readable error code (e.g., `ERR_3001`) |\n        | `retryable` | Whether the client should retry the request |\n        | `guidance` | User-facing guidance for resolution |\n        | `requestId` | Unique request trace ID for support |\n\n        See [Error Codes Reference](/error-codes) for the full list.",
    "license": {
      "name": "MIT",
      "url": "https://opensource.org/licenses/MIT"
    },
    "title": "Solo Boss Cloud API",
    "version": "4.72.0"
  },
  "openapi": "3.2.0",
  "paths": {
    "/.well-known/oauth-protected-resource": {
      "get": {
        "description": "RFC 9728 document named by the `resource_metadata` parameter of the 401 challenge from POST /mcp. Public; cacheable for an hour.",
        "operationId": "getMcpProtectedResourceMetadata",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/McpProtectedResourceMetadata"
                }
              }
            },
            "description": "Metadata"
          }
        },
        "security": [],
        "summary": "OAuth Protected Resource Metadata for the MCP connector",
        "tags": [
          "MCP Connector"
        ]
      }
    },
    "/accounting-settings": {
      "get": {
        "description": "Retrieve current accounting settings for frontend UI adaptation.\n\n## Frontend Use Cases\n\n### 1. Show/Hide Manual Post Button\n```typescript\nconst { autoPostJournals } = await getAccountingSettings()\nif (!autoPostJournals) {\n  // Show \"元帳に転記\" button for manual posting\n}\n```\n\n### 2. Display Auto-Post Indicator\n```typescript\nconst { mode, description } = await getAccountingSettings()\nif (mode === 'auto') {\n  // Show \"(自動転記)\" badge on journal entries\n  // tooltip: description\n}\n```\n\n### 3. Show Pending Drafts Count\n```typescript\nconst { pendingDraftsCount } = await getAccountingSettings()\nif (pendingDraftsCount > 0) {\n  // Show \"未転記 {count} 件\" badge\n}\n```\n\n## Workflow Modes\n\n| Mode | AUTO_POST_JOURNALS | Behavior |\n|------|-------------------|----------|\n| auto | true | Documents → Journal → Auto-Post → Trial Balance |\n| manual | false | Documents → Journal (draft) → Manual Post → Trial Balance |\n\n## Default Behavior\n- Development: `auto` (immediate trial balance updates)\n- Production: `manual` (accountant review before posting)\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "auto_mode": {
                    "summary": "Auto-post enabled (development)",
                    "value": {
                      "data": {
                        "autoPostJournals": true,
                        "description": "自動転記モード: 仕訳は確認後自動的に元帳に転記されます",
                        "mode": "auto",
                        "pendingDraftsCount": 0
                      },
                      "message": "Accounting settings retrieved successfully",
                      "statusCode": 200
                    }
                  },
                  "manual_mode": {
                    "summary": "Manual posting mode (production)",
                    "value": {
                      "data": {
                        "autoPostJournals": false,
                        "description": "手動転記モード: 仕訳を確認後、手動で元帳に転記してください",
                        "mode": "manual",
                        "pendingDraftsCount": 7
                      },
                      "message": "Accounting settings retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/AccountingSettingsResponse"
                }
              }
            },
            "description": "Accounting settings retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get current accounting configuration",
        "tags": [
          "Accounting Settings"
        ]
      }
    },
    "/accounting/classify-transaction": {
      "post": {
        "description": "Classify a bank transaction using rule-based keyword matching.\n\n## How It Works\n1. Transaction description is matched against `TRANSACTION_RULES` keywords\n2. Matching rules provide debit/credit accounts, tax rates, and remarks\n3. If no exact match, suggestions are provided based on partial matches\n\n## Use Cases\n- Automatic categorization of bank transactions\n- Pre-filling journal entry forms\n- Batch classification of imported transactions",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ClassifyTransactionRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ClassifyTransactionResponse"
                }
              }
            },
            "description": "Transaction classified successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Classify a transaction by description (取引分類)",
        "tags": [
          "Accounting Logic"
        ]
      }
    },
    "/accounting/detect-transfer": {
      "post": {
        "description": "Detect if a bank transaction is an inter-account transfer by finding matching opposite transactions.\n\n## Detection Logic\n1. Finds the source transaction by ID\n2. Searches other bank accounts for matching amount (opposite direction) within date tolerance\n3. Returns matching transaction if found\n\n## Parameters\n- `date_tolerance_days`: How many days to search around the transaction date (default: 3)",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/DetectTransferRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DetectTransferResponse"
                }
              }
            },
            "description": "Transfer detection result"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Detect inter-account transfer (振替検出)",
        "tags": [
          "Accounting Logic"
        ]
      }
    },
    "/accounting/dock-summary": {
      "get": {
        "description": "Retrieve a consolidated accounting dock summary in a single API call.\n\n## What's Included\n- Journal entry counts (by status and source type)\n- General ledger account count and balance verification\n- Trial balance summary with discrepancy check\n- Expense document journalization stats\n- Bank statement journalization stats\n- Pending draft count\n\n## Query Parameters\nOptional date range to scope the summary to a fiscal period.\nIf omitted, returns all-time summary.\n\n## Performance\n- **Target**: <300ms response time\n- **Caching**: 60-second per-user memory cache\n- **Queries**: 9 parallel database queries via Promise.all()\n\n## Use Cases\n- Accounting dock page initial load (replaces 5+ API calls)\n- Workflow status indicators (balanced, journalized counts)\n- 貸借一致 verification (server-authoritative)",
        "parameters": [
          {
            "description": "Start date in YYYYMMDD format (e.g., fiscal period start)",
            "example": 20250401,
            "in": "query",
            "name": "start_date",
            "required": false,
            "schema": {
              "maximum": 99991231,
              "minimum": 19000101,
              "type": "integer"
            }
          },
          {
            "description": "End date in YYYYMMDD format (e.g., fiscal period end)",
            "example": 20260331,
            "in": "query",
            "name": "end_date",
            "required": false,
            "schema": {
              "maximum": 99991231,
              "minimum": 19000101,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DockSummaryResponse"
                }
              }
            },
            "description": "Dock summary retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get composite dock summary",
        "tags": [
          "Accounting Dock"
        ]
      }
    },
    "/accounting/generate-journal-entry": {
      "post": {
        "description": "Generate a journal entry from a bank transaction using rule-based classification.\n\n## Process\n1. Fetches the bank transaction by ID\n2. Classifies the transaction using keyword rules\n3. Generates a complete journal entry with accounts, amounts, and tax\n\n## Override Support\nOptional `override_accounts` allows manually specifying debit/credit account codes\ninstead of relying on automatic classification.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/GenerateJournalEntryRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GenerateJournalEntryResponse"
                }
              }
            },
            "description": "Journal entry generated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Generate journal entry from transaction (仕訳生成)",
        "tags": [
          "Accounting Logic"
        ]
      }
    },
    "/accounts": {
      "get": {
        "description": "Retrieve a list of all accounts in the Chart of Accounts with optional filtering by type and active status.\n\n## Query Parameters\n- **type**: Filter accounts by accounting type (asset, liability, equity, revenue, expense)\n- **is_active**: Filter by active status (defaults to true if not specified)\n\n## Response\nReturns an array of account objects with complete account information including:\n- Account identification (ID, code, name)\n- Classification (type, subType, normalSide)\n- Status and metadata (isActive, timestamps)\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Filter accounts by type",
            "in": "query",
            "name": "type",
            "required": false,
            "schema": {
              "enum": [
                "asset",
                "liability",
                "equity",
                "revenue",
                "expense"
              ],
              "type": "string"
            }
          },
          {
            "description": "Filter by active status (defaults to true)",
            "in": "query",
            "name": "is_active",
            "required": false,
            "schema": {
              "type": "boolean"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AccountListResponse"
                }
              }
            },
            "description": "Accounts retrieved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List all accounts with optional filtering",
        "tags": [
          "Accounts"
        ]
      }
    },
    "/accounts/code/{code}": {
      "get": {
        "description": "Retrieve a specific account by its unique account code.\n\n## Path Parameters\n- **code**: Account code (e.g., \"1000\", \"2000\", \"3000\")\n\n## Account Codes\nAccount codes follow standard accounting numbering conventions:\n- **1000-1999**: Asset accounts\n- **2000-2999**: Liability accounts  \n- **3000-3999**: Equity accounts\n- **4000-4999**: Revenue accounts\n- **5000-5999**: Expense accounts\n\n## Response\nReturns complete account information for the specified code.\n\n## Use Cases\n- Quick account lookup by code\n- Integration with external accounting systems\n- Data import/export operations\n- Account validation in transactions\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Account code to lookup",
            "example": "1000",
            "in": "path",
            "name": "code",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AccountResponse"
                }
              }
            },
            "description": "Account retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get account by code",
        "tags": [
          "Accounts"
        ]
      }
    },
    "/accounts/grouped": {
      "get": {
        "description": "Retrieve all active accounts organized by accounting type for easy categorization and display.\n\n## Response Structure\nReturns accounts grouped into five main categories:\n- **asset**: Asset accounts (cash, receivables, inventory, etc.)\n- **liability**: Liability accounts (payables, loans, accruals, etc.)\n- **equity**: Equity accounts (capital, retained earnings, etc.)\n- **revenue**: Revenue accounts (sales, service income, etc.)\n- **expense**: Expense accounts (operating costs, utilities, etc.)\n\n## Use Cases\n- Chart of Accounts display in accounting software\n- Financial statement preparation\n- Account selection dropdowns in transactions\n- Accounting reports and analysis\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GroupedAccountsResponse"
                }
              }
            },
            "description": "Grouped accounts retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get accounts grouped by type",
        "tags": [
          "Accounts"
        ]
      }
    },
    "/accounts/{account_id}": {
      "get": {
        "description": "Retrieve a specific account by its unique identifier.\n\n## Path Parameters\n- **account_id**: UUID of the account to retrieve\n\n## Response\nReturns complete account information including:\n- Account identification and naming\n- Type classification and normal balance side\n- Active status and timestamps\n- Description and sub-type details\n\n## Use Cases\n- Account detail views\n- Transaction validation\n- Account management operations\n- Financial reporting\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the account to retrieve",
            "in": "path",
            "name": "account_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AccountResponse"
                }
              }
            },
            "description": "Account retrieved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get account by ID",
        "tags": [
          "Accounts"
        ]
      }
    },
    "/admin/logs": {
      "delete": {
        "description": "Clears the in-memory log buffer, removing all stored log entries.\n      \n## Security Warning\n- **Admin Only**: This operation requires admin-level authentication\n- **Irreversible**: Cleared logs cannot be recovered\n- **Audit Trail**: Clear operations are logged for security audit\n- **Impact**: Affects real-time monitoring and debugging capabilities\n\n## Use Cases\n- **Buffer Maintenance**: Clear buffer when it becomes too large\n- **Privacy Compliance**: Remove logs containing sensitive information\n- **System Reset**: Clean slate for testing or maintenance\n- **Storage Management**: Free up memory used by log buffer",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-clear": {
                    "summary": "Successful log buffer clear",
                    "value": {
                      "message": "Log buffer cleared",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ClearLogsResponse"
                }
              }
            },
            "description": "Log buffer cleared successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "content": {
              "application/json": {
                "examples": {
                  "clear-error": {
                    "summary": "Error clearing log buffer",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "Failed to clear log buffer",
                      "statusCode": 500
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Clear log buffer (admin only)",
        "tags": [
          "Admin Logs"
        ]
      },
      "get": {
        "description": "Retrieves recent log entries from the in-memory buffer with comprehensive filtering options.\n      \n## Log Filtering\n- **Level Filtering**: Filter by log level (error, warn, info, debug)\n- **Context Filtering**: Filter by log context or module name\n- **Time Range**: Filter logs within specific time ranges\n- **User/Request Tracking**: Filter by user ID or request ID\n- **Text Search**: Search within log messages and metadata\n\n## Log Buffer Management\n- **In-Memory Storage**: Logs stored in circular buffer for fast access\n- **Buffer Size**: Configurable buffer size with automatic rotation\n- **Real-Time Updates**: Buffer updated in real-time as logs are generated\n- **Performance**: Optimized for high-frequency log operations\n\n## Security Features\n- **Authentication Required**: All admin log access requires authentication\n- **Audit Logging**: All log access attempts are audited\n- **Demo Guard**: Additional protection against demo environment access\n- **IP Tracking**: Request IP addresses logged for security monitoring\n\n## Use Cases\n- **Debugging**: Real-time debugging of application issues\n- **Monitoring**: System health and performance monitoring\n- **Security Analysis**: Security event investigation and analysis\n- **Performance Tracking**: Application performance analysis",
        "parameters": [
          {
            "description": "Filter by log level",
            "in": "query",
            "name": "level",
            "required": false,
            "schema": {
              "enum": [
                "error",
                "warn",
                "info",
                "debug"
              ],
              "type": "string"
            }
          },
          {
            "description": "Filter by context",
            "in": "query",
            "name": "context",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "Filter by request ID",
            "in": "query",
            "name": "requestId",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "Filter by user ID",
            "in": "query",
            "name": "userId",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "Search in log messages",
            "in": "query",
            "name": "search",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "Filter logs after this time (ISO format)",
            "in": "query",
            "name": "startTime",
            "required": false,
            "schema": {
              "format": "date-time",
              "type": "string"
            }
          },
          {
            "description": "Filter logs before this time (ISO format)",
            "in": "query",
            "name": "endTime",
            "required": false,
            "schema": {
              "format": "date-time",
              "type": "string"
            }
          },
          {
            "description": "Maximum number of logs to return",
            "in": "query",
            "name": "limit",
            "required": false,
            "schema": {
              "default": 100,
              "maximum": 10000,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-logs-retrieval": {
                    "summary": "Successful logs retrieval with filtering",
                    "value": {
                      "data": [
                        {
                          "context": "auth",
                          "level": "info",
                          "message": "User authentication successful",
                          "metadata": {
                            "ip": "192.168.1.1",
                            "userAgent": "Mozilla/5.0..."
                          },
                          "requestId": "req_123456",
                          "timestamp": "2024-01-15T10:30:00.000Z",
                          "userId": "user_789"
                        },
                        {
                          "context": "database",
                          "level": "error",
                          "message": "Database connection timeout",
                          "metadata": {
                            "retries": 3,
                            "timeout": 5000
                          },
                          "requestId": "req_123455",
                          "timestamp": "2024-01-15T10:29:45.000Z"
                        }
                      ],
                      "message": "Retrieved 50 log entries",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/LogsResponse"
                }
              }
            },
            "description": "Logs retrieved successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "examples": {
                  "invalid-date-format": {
                    "summary": "Invalid date format in time filters",
                    "value": {
                      "error": "Bad Request",
                      "message": "Invalid date format in startTime or endTime parameter",
                      "statusCode": 400
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Invalid query parameters"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "content": {
              "application/json": {
                "examples": {
                  "log-service-error": {
                    "summary": "Log service error",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "Failed to retrieve logs from buffer",
                      "statusCode": 500
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get recent logs with filtering",
        "tags": [
          "Admin Logs"
        ]
      }
    },
    "/admin/logs/export": {
      "get": {
        "description": "Exports filtered logs as a downloadable JSON file for external analysis or archival.\n      \n## Export Features\n- **Filtered Export**: Apply same filters as log retrieval\n- **JSON Format**: Standard JSON format for easy parsing\n- **Large Datasets**: Supports export of up to 10,000 log entries\n- **File Download**: Direct file download with appropriate headers\n\n## Export Options\n- **Level Filtering**: Export only specific log levels\n- **Context Filtering**: Export logs from specific contexts\n- **Search Filtering**: Export logs matching search criteria\n- **Time Range**: Export logs within specific time periods\n\n## Use Cases\n- **Log Archival**: Archive logs for long-term storage\n- **External Analysis**: Export for analysis in external tools\n- **Compliance**: Export logs for regulatory compliance requirements\n- **Backup**: Create backup copies of important log data",
        "parameters": [
          {
            "description": "Filter exported logs by level",
            "in": "query",
            "name": "level",
            "required": false,
            "schema": {
              "enum": [
                "error",
                "warn",
                "info",
                "debug"
              ],
              "type": "string"
            }
          },
          {
            "description": "Filter exported logs by context",
            "in": "query",
            "name": "context",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "Search filter for exported logs",
            "in": "query",
            "name": "search",
            "required": false,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "description": "JSON file containing exported logs",
                  "format": "binary",
                  "type": "string"
                }
              }
            },
            "description": "Logs exported successfully",
            "headers": {
              "Content-Disposition": {
                "description": "File download header",
                "schema": {
                  "example": "attachment; filename=logs-1642248600000.json",
                  "type": "string"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "content": {
              "application/json": {
                "examples": {
                  "export-error": {
                    "summary": "Error exporting logs",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "Failed to export log data",
                      "statusCode": 500
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Export logs as JSON file download",
        "tags": [
          "Admin Logs"
        ]
      }
    },
    "/admin/logs/stats": {
      "get": {
        "description": "Retrieves comprehensive statistics about the current log buffer contents.\n      \n## Statistics Overview\n- **Total Counts**: Overall log entry counts in buffer\n- **Level Distribution**: Breakdown of logs by severity level\n- **Context Analysis**: Distribution of logs by application context\n- **Recent Errors**: Latest error entries for quick issue identification\n\n## Metrics Details\n- **Performance Indicators**: Log volume and distribution patterns\n- **Error Tracking**: Recent error patterns and frequencies\n- **System Health**: Overall application logging health\n- **Trend Analysis**: Log level trends and patterns\n\n## Use Cases\n- **Dashboard Widgets**: Display log statistics in admin dashboards\n- **Health Monitoring**: Quick overview of system health via log patterns\n- **Error Alerting**: Identify error spikes and patterns\n- **Capacity Planning**: Monitor log buffer usage and patterns",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-stats": {
                    "summary": "Successful log statistics retrieval",
                    "value": {
                      "data": {
                        "byContext": {
                          "api": 450,
                          "auth": 300,
                          "database": 250,
                          "system": 500
                        },
                        "byLevel": {
                          "debug": 240,
                          "error": 15,
                          "info": 1200,
                          "warn": 45
                        },
                        "recentErrors": [
                          {
                            "context": "database",
                            "level": "error",
                            "message": "Database connection timeout",
                            "requestId": "req_123456",
                            "timestamp": "2024-01-15T10:30:00.000Z"
                          }
                        ],
                        "total": 1500
                      },
                      "message": "Log statistics retrieved",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/LogStatsResponse"
                }
              }
            },
            "description": "Log statistics retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "content": {
              "application/json": {
                "examples": {
                  "stats-error": {
                    "summary": "Error retrieving log statistics",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "Failed to generate log statistics",
                      "statusCode": 500
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get log statistics and metrics",
        "tags": [
          "Admin Logs"
        ]
      }
    },
    "/admin/logs/stream": {
      "get": {
        "description": "Establishes a Server-Sent Events connection for real-time log streaming.\n      \n## Real-Time Streaming\n- **Server-Sent Events**: Uses SSE for real-time log updates\n- **Live Updates**: Logs streamed as they are generated\n- **Connection Management**: Automatic heartbeat and reconnection\n- **Event Types**: Connected, heartbeat, and log events\n\n## Stream Features\n- **Low Latency**: Near real-time log delivery\n- **Connection Persistence**: Long-lived connections with heartbeat\n- **Auto-Reconnect**: Client can automatically reconnect on disconnect\n- **Event Filtering**: Future support for filtered streaming\n\n## Event Format\n- **Connected**: Initial connection confirmation\n- **Heartbeat**: Keep-alive events every 30 seconds\n- **Log**: Actual log entries as they occur\n- **JSON Format**: All events in structured JSON format\n\n## Use Cases\n- **Live Monitoring**: Real-time system monitoring dashboards\n- **Debug Sessions**: Live debugging of application issues\n- **Alert Systems**: Real-time error detection and alerting\n- **Development**: Live log viewing during development",
        "responses": {
          "200": {
            "content": {
              "text/event-stream": {
                "schema": {
                  "description": "Server-Sent Events stream with log data",
                  "example": "data: {\"type\":\"connected\",\"timestamp\":\"2024-01-15T10:30:00.000Z\"}\n\ndata: {\"type\":\"log\",\"timestamp\":\"2024-01-15T10:30:01.000Z\",\"data\":{\"level\":\"info\",\"message\":\"User logged in\"}}\n\n",
                  "type": "string"
                }
              }
            },
            "description": "Server-Sent Events stream established",
            "headers": {
              "Cache-Control": {
                "schema": {
                  "example": "no-cache",
                  "type": "string"
                }
              },
              "Connection": {
                "schema": {
                  "example": "keep-alive",
                  "type": "string"
                }
              },
              "Content-Type": {
                "schema": {
                  "example": "text/event-stream",
                  "type": "string"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "content": {
              "application/json": {
                "examples": {
                  "stream-error": {
                    "summary": "Error establishing log stream",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "Failed to establish log streaming connection",
                      "statusCode": 500
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Real-time log streaming via Server-Sent Events",
        "tags": [
          "Admin Logs"
        ]
      }
    },
    "/admin/logs/trace/{requestId}": {
      "get": {
        "description": "Retrieves all log entries associated with a specific request ID for complete request tracing.\n      \n## Request Tracing\n- **Complete Timeline**: All logs for a specific request in chronological order\n- **Cross-Module Tracking**: Logs from all application modules for the request\n- **Debug Support**: Complete request flow for debugging complex issues\n- **Performance Analysis**: Request timing and performance insights\n\n## Correlation Features\n- **Request ID Matching**: Finds all logs with matching request correlation ID\n- **Chronological Order**: Logs sorted by timestamp for flow analysis\n- **Context Preservation**: Maintains all log context and metadata\n- **Error Tracking**: Identifies errors within specific request flows\n\n## Use Cases\n- **Bug Investigation**: Trace specific request flows that caused issues\n- **Performance Debugging**: Analyze request performance and bottlenecks\n- **User Support**: Investigate specific user-reported issues\n- **System Analysis**: Understand request flows across system components",
        "parameters": [
          {
            "description": "Request correlation ID to trace",
            "in": "path",
            "name": "requestId",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-trace": {
                    "summary": "Successful request trace retrieval",
                    "value": {
                      "data": [
                        {
                          "context": "api",
                          "level": "info",
                          "message": "Request received",
                          "metadata": {
                            "method": "POST",
                            "path": "/api/users"
                          },
                          "requestId": "req_123456",
                          "timestamp": "2024-01-15T10:30:00.000Z"
                        },
                        {
                          "context": "validation",
                          "level": "debug",
                          "message": "Validating request data",
                          "requestId": "req_123456",
                          "timestamp": "2024-01-15T10:30:01.000Z"
                        },
                        {
                          "context": "api",
                          "level": "info",
                          "message": "Request processed successfully",
                          "metadata": {
                            "duration": 2000,
                            "status": 200
                          },
                          "requestId": "req_123456",
                          "timestamp": "2024-01-15T10:30:02.000Z"
                        }
                      ],
                      "message": "Found 5 log entries for request",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/RequestTraceResponse"
                }
              }
            },
            "description": "Request trace retrieved successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "examples": {
                  "invalid-request-id": {
                    "summary": "Invalid or missing request ID",
                    "value": {
                      "error": "Bad Request",
                      "message": "Request ID parameter is required and must be a valid string",
                      "statusCode": 400
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Invalid request ID parameter"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "examples": {
                  "no-logs-found": {
                    "summary": "No logs found for request",
                    "value": {
                      "error": "Not Found",
                      "message": "No log entries found for the specified request ID",
                      "statusCode": 404
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "No logs found for request ID"
          },
          "500": {
            "content": {
              "application/json": {
                "examples": {
                  "trace-error": {
                    "summary": "Error retrieving request trace",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "Failed to retrieve request trace logs",
                      "statusCode": 500
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get all logs for a specific request (request tracing)",
        "tags": [
          "Admin Logs"
        ]
      }
    },
    "/admin/migrations": {
      "get": {
        "description": "Retrieves the complete database migration history from Prisma migrations table.\n      \n## Migration History\n- **Complete Timeline**: All applied migrations in chronological order\n- **Migration Details**: ID, name, application timestamp, and checksum\n- **Database Integration**: Direct query from Prisma migrations table\n- **Reverse Chronological**: Latest migrations first for easy review\n\n## Migration Information\n- **Migration ID**: Unique identifier for each migration\n- **Migration Name**: Human-readable migration name with timestamp\n- **Applied At**: Exact timestamp when migration was applied\n- **Checksum**: Migration file checksum for integrity verification\n\n## Use Cases\n- **Deployment Tracking**: Track database schema changes across deployments\n- **Rollback Planning**: Understand migration history for rollback decisions\n- **Audit Trail**: Maintain audit trail of database schema changes\n- **Troubleshooting**: Identify when specific schema changes were applied",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-migrations": {
                    "summary": "Successful migration history retrieval",
                    "value": {
                      "data": [
                        {
                          "applied_at": "2024-01-15T10:30:00.000Z",
                          "checksum": "abc123def456789",
                          "id": "20240115103000_init",
                          "name": "20240115103000_init"
                        },
                        {
                          "applied_at": "2024-01-10T14:50:00.000Z",
                          "checksum": "def456ghi789abc",
                          "id": "20240110145000_add_users",
                          "name": "20240110145000_add_users"
                        },
                        {
                          "applied_at": "2024-01-05T12:00:00.000Z",
                          "checksum": "ghi789abc123def",
                          "id": "20240105120000_initial_schema",
                          "name": "20240105120000_initial_schema"
                        }
                      ],
                      "message": "Found 15 migrations",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/MigrationsResponse"
                }
              }
            },
            "description": "Migration history retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "content": {
              "application/json": {
                "examples": {
                  "database-error": {
                    "summary": "Database query error",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "Failed to retrieve migration history from database",
                      "statusCode": 500
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get migration history",
        "tags": [
          "Admin Logs"
        ]
      }
    },
    "/admin/migrations/status": {
      "get": {
        "description": "Retrieves current database migration status including applied and pending migrations.\n      \n## Migration Status Overview\n- **Total Migrations**: Count of all applied migrations\n- **Last Migration**: Details of the most recently applied migration\n- **Pending Migrations**: List of migrations waiting to be applied\n- **Schema Version**: Current database schema version\n\n## Status Information\n- **Applied Count**: Total number of successfully applied migrations\n- **Latest Migration**: Most recent migration with full details\n- **Pending Detection**: Automatic detection of unapplied migrations\n- **Version Tracking**: Current schema version from package.json\n\n## Pending Migration Detection\n- **File System Scan**: Scans migration directory for new files\n- **Applied Comparison**: Compares with database migration records\n- **Automatic Detection**: Identifies migrations not yet applied\n- **Deployment Ready**: Shows if system is ready for deployment\n\n## Use Cases\n- **Deployment Checks**: Verify migration status before deployment\n- **Development Status**: Check if local database is up to date\n- **CI/CD Integration**: Automated migration status checks\n- **System Health**: Ensure database schema is current",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-status": {
                    "summary": "Successful migration status retrieval",
                    "value": {
                      "data": {
                        "lastMigration": {
                          "applied_at": "2024-01-15T10:30:00.000Z",
                          "checksum": "abc123def456789",
                          "id": "20240115103000_init",
                          "name": "20240115103000_init"
                        },
                        "pendingMigrations": [
                          "20240116120000_add_indexes",
                          "20240117090000_update_constraints"
                        ],
                        "schemaVersion": "1.2.3",
                        "totalMigrations": 15
                      },
                      "message": "Migration status retrieved",
                      "statusCode": 200
                    }
                  },
                  "up-to-date-status": {
                    "summary": "System up to date with no pending migrations",
                    "value": {
                      "data": {
                        "lastMigration": {
                          "applied_at": "2024-01-15T10:30:00.000Z",
                          "checksum": "abc123def456789",
                          "id": "20240115103000_init",
                          "name": "20240115103000_init"
                        },
                        "pendingMigrations": [],
                        "schemaVersion": "1.2.3",
                        "totalMigrations": 15
                      },
                      "message": "Migration status retrieved",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/MigrationStatusResponse"
                }
              }
            },
            "description": "Migration status retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "content": {
              "application/json": {
                "examples": {
                  "filesystem-error": {
                    "summary": "Error reading migration files",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "Failed to read migration directory",
                      "statusCode": 500
                    }
                  },
                  "status-error": {
                    "summary": "Error retrieving migration status",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "Failed to retrieve migration status",
                      "statusCode": 500
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get current migration status",
        "tags": [
          "Admin Logs"
        ]
      }
    },
    "/advisories": {
      "get": {
        "description": "取引先・契約・今期と前期の支払から、源泉徴収・租税条約・消費税・印紙税などの注意点を返します。読み取りのみで、何も書き込みません。",
        "parameters": [
          {
            "in": "query",
            "name": "targetKind",
            "schema": {
              "enum": [
                "counterparty",
                "agreement",
                "journal_entry",
                "bank_transaction",
                "company",
                "expense"
              ],
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "targetId",
            "schema": {
              "maxLength": 64,
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "advisories": {
                          "items": {
                            "$ref": "#/components/schemas/Advisory"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "アドバイス"
          },
          "400": {
            "description": "入力エラー"
          },
          "401": {
            "description": "未認証"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "契約・支払のアドバイス一覧",
        "tags": [
          "Advisories"
        ]
      }
    },
    "/advisories/acknowledge": {
      "post": {
        "description": "誰が・いつ・なぜ確認したかを確認記録（finding_acknowledgments）に追記します。取り消しは /findings/acknowledgments/{id}/revoke。",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "keys": {
                    "items": {
                      "type": "string"
                    },
                    "maxItems": 50,
                    "minItems": 1,
                    "type": "array"
                  },
                  "reason": {
                    "maxLength": 2000,
                    "minLength": 8,
                    "type": "string"
                  }
                },
                "required": [
                  "keys",
                  "reason"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "acknowledged": {
                          "items": {
                            "properties": {
                              "acknowledgment": {
                                "$ref": "#/components/schemas/AdvisoryAcknowledgment"
                              },
                              "key": {
                                "type": "string"
                              }
                            },
                            "required": [
                              "key",
                              "acknowledgment"
                            ],
                            "type": "object"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "記録しました"
          },
          "400": {
            "description": "入力エラー"
          },
          "401": {
            "description": "未認証"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "アドバイスの確認を記録",
        "tags": [
          "Advisories"
        ]
      }
    },
    "/advisories/counterparties/{clientId}": {
      "get": {
        "parameters": [
          {
            "in": "path",
            "name": "clientId",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/CounterpartyAdvice"
                    },
                    "message": {
                      "type": "string"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "プロフィールとアドバイス"
          },
          "401": {
            "description": "未認証"
          },
          "404": {
            "description": "取引先が見つかりません"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "取引先の税務プロフィールとアドバイス",
        "tags": [
          "Advisories"
        ]
      },
      "put": {
        "description": "記録後にアドバイスを評価し、判断できない源泉徴収の論点は未解決論点として登録します（同じ取引先の論点を既にお持ちなら登録しません）。",
        "parameters": [
          {
            "in": "path",
            "name": "clientId",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "countryCode": {
                    "example": "VN",
                    "nullable": true,
                    "pattern": "^[A-Z]{2}$",
                    "type": "string"
                  },
                  "entityType": {
                    "enum": [
                      "corporation",
                      "individual"
                    ],
                    "nullable": true,
                    "type": "string"
                  },
                  "residency": {
                    "enum": [
                      "domestic",
                      "foreign"
                    ],
                    "nullable": true,
                    "type": "string"
                  },
                  "residencyDocumentNote": {
                    "maxLength": 500,
                    "nullable": true,
                    "type": "string"
                  },
                  "treatyFormFiledOn": {
                    "format": "date",
                    "nullable": true,
                    "type": "string"
                  }
                },
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/CounterpartyAdvice"
                    },
                    "message": {
                      "type": "string"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "保存後のプロフィールとアドバイス"
          },
          "400": {
            "description": "入力エラー"
          },
          "401": {
            "description": "未認証"
          },
          "404": {
            "description": "取引先が見つかりません"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "取引先の所在国・法人/個人・租税条約届出日を記録",
        "tags": [
          "Advisories"
        ]
      }
    },
    "/advisories/payment-check": {
      "get": {
        "description": "その明細をこの勘定科目・税区分で仕訳したときに出るアドバイス（警告のみ・仕訳を止めません）。",
        "parameters": [
          {
            "in": "query",
            "name": "bankTransactionId",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "example": "509",
            "in": "query",
            "name": "accountCode",
            "required": true,
            "schema": {
              "maxLength": 20,
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "taxType",
            "schema": {
              "maximum": 5,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "advisories": {
                          "items": {
                            "$ref": "#/components/schemas/Advisory"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "アドバイス"
          },
          "400": {
            "description": "入力エラー"
          },
          "401": {
            "description": "未認証"
          },
          "404": {
            "description": "明細が見つかりません"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "銀行明細を仕訳する前のアドバイス",
        "tags": [
          "Advisories"
        ]
      }
    },
    "/ai-business-support/purchase-recommendations": {
      "get": {
        "description": "Generate intelligent purchase recommendations based on company business purpose and tax optimization.\n\n## AI Purchase Recommendations (AI購入推奨)\nIntelligent business purchase guidance with:\n- **Business Purpose Analysis**: Analysis of company Teikan (articles of incorporation) for relevant purchases\n- **Tax Optimization**: Recommendations optimized for Japanese tax benefits and deductions\n- **Budget-Based Filtering**: Recommendations within specified budget limits (¥100,000 or ¥300,000)\n- **Risk Assessment**: Tax and compliance risk evaluation for each recommendation\n- **Practical Guidance**: Actionable purchase guidance with search keywords and alternatives\n\n## Tax Treatment Optimization\n- **少額減価償却資産**: Small asset depreciation for items under ¥100,000\n- **中小企業者等の特例**: SME special provisions for items under ¥300,000\n- **Immediate Deduction**: Identification of items eligible for immediate tax deduction\n- **Compliance Requirements**: Guidance on documentation and compliance requirements\n\n## Business Justification\n- **Teikan Analysis**: AI analysis of company's registered business purposes\n- **Relevance Scoring**: Scoring of purchase relevance to business operations\n- **Purpose Alignment**: Alignment of purchases with registered business activities\n- **Risk Mitigation**: Identification and mitigation of business purpose risks\n\n## Recommendation Features\n- **Product Categories**: Filtering by specific product categories\n- **Price Estimation**: Realistic price estimates with ranges\n- **Search Optimization**: Amazon search keywords for easy procurement\n- **Alternative Suggestions**: Alternative products and options\n- **Priority Ranking**: Priority-based ranking for purchase decisions\n\n## Budget Thresholds\n- **¥100,000 Limit**: Small asset depreciation threshold for immediate deduction\n- **¥300,000 Limit**: SME special provision threshold for enhanced tax benefits\n- **Cost Optimization**: Recommendations optimized for maximum tax benefits within budget\n- **ROI Analysis**: Return on investment analysis for business purchases\n\n## Rate Limiting\n- **AI Operations**: Limited to 30 requests per 15 minutes per user\n- **Cost Management**: Rate limiting to manage AI API costs and ensure fair usage\n- **Performance Optimization**: Prevent system overload from excessive AI requests\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Company ID for recommendations",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "in": "query",
            "name": "companyId",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Budget limit for recommendations (default: 300000)",
            "example": 300000,
            "in": "query",
            "name": "budgetLimit",
            "required": false,
            "schema": {
              "default": 300000,
              "enum": [
                100000,
                300000
              ],
              "type": "integer"
            }
          },
          {
            "description": "Comma-separated list of product categories to focus on",
            "example": "office_equipment,software,furniture",
            "in": "query",
            "name": "categories",
            "required": false,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PurchaseRecommendationsResponse"
                }
              }
            },
            "description": "Purchase recommendations retrieved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "message": {
                      "example": "Too many AI requests, please try again later",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Rate limit exceeded"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get AI-powered purchase recommendations",
        "tags": [
          "AI Business Support"
        ]
      }
    },
    "/ai-business-support/tax-audit/analyze": {
      "post": {
        "description": "Initiate comprehensive AI-powered tax audit analysis for risk detection and compliance assessment.\n\n## AI Tax Audit Analysis (AI税務監査分析)\nComprehensive tax compliance analysis with:\n- **Risk Detection**: AI-powered identification of tax compliance risks and issues\n- **Multi-Source Analysis**: Integration of journal entries, general ledger, cash book, and expense reports\n- **Compliance Scoring**: Quantitative compliance assessment with detailed scoring\n- **Issue Classification**: Categorization of issues by severity (critical, warning, info)\n- **Actionable Recommendations**: Specific recommendations for compliance improvement\n- **Japanese Tax Law**: Compliance with Japanese tax regulations and requirements\n\n## Analysis Scope\n- **Document Analysis**: Comprehensive analysis of accounting documents and transactions\n- **Pattern Recognition**: AI-powered detection of unusual patterns and potential issues\n- **Regulatory Compliance**: Verification against Japanese tax law requirements\n- **Risk Assessment**: Quantitative and qualitative risk assessment\n- **Trend Analysis**: Historical trend analysis for compliance patterns\n\n## Asynchronous Processing\n- **Background Processing**: Long-running analysis processed in background\n- **Job Tracking**: Unique job ID for progress tracking and result retrieval\n- **Progress Updates**: Real-time progress updates through status polling\n- **Result Persistence**: Analysis results stored for future reference\n\n## AI-Powered Features\n- **Natural Language Processing**: Analysis of document content and descriptions\n- **Pattern Recognition**: Detection of compliance patterns and anomalies\n- **Risk Scoring**: Intelligent risk assessment based on multiple factors\n- **Recommendation Engine**: AI-generated recommendations for improvement\n- **Compliance Intelligence**: Knowledge of Japanese tax law and best practices\n\n## Rate Limiting\n- **AI Operations**: Limited to 30 requests per 15 minutes per user\n- **Cost Management**: Rate limiting to manage AI API costs\n- **Fair Usage**: Ensure fair access to AI resources across users\n- **Performance Optimization**: Prevent system overload from excessive AI requests\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/TaxAuditAnalyzeRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "202": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/TaxAuditStartResponse"
                }
              }
            },
            "description": "Tax audit analysis started successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "message": {
                      "example": "Too many AI requests, please try again later",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Rate limit exceeded"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Start AI-powered tax audit analysis",
        "tags": [
          "AI Business Support"
        ]
      }
    },
    "/ai-business-support/tax-audit/status/{jobId}": {
      "get": {
        "description": "Retrieve the current status and results of a tax audit analysis job.\n\n## Job Status Tracking (ジョブステータス追跡)\nReal-time job monitoring with:\n- **Progress Tracking**: Real-time progress updates with percentage completion\n- **Status Information**: Current job status (pending, processing, completed, failed)\n- **Result Delivery**: Complete analysis results when job is completed\n- **Error Handling**: Detailed error information if job fails\n- **Performance Metrics**: Job timing and performance information\n\n## Job Lifecycle\n- **Pending**: Job created and queued for processing\n- **Processing**: AI analysis in progress with progress updates\n- **Completed**: Analysis finished with full results available\n- **Failed**: Job failed with error details and recovery information\n\n## Result Structure\n- **Compliance Summary**: Overall risk assessment and issue counts\n- **Detailed Issues**: Comprehensive list of identified issues with severity levels\n- **Recommendations**: Actionable recommendations for compliance improvement\n- **Compliance Score**: Quantitative compliance assessment (0-100)\n- **Analysis Metadata**: Analysis date, scope, and processing information\n\n## Polling Guidelines\n- **Frequency**: Poll every 5-10 seconds for active jobs\n- **Rate Limiting**: 60 requests per minute for status polling\n- **Completion Detection**: Stop polling when status is 'completed' or 'failed'\n- **Timeout Handling**: Handle long-running jobs with appropriate timeouts\n\n## Use Cases\n- **Progress Monitoring**: Track analysis progress for user feedback\n- **Result Retrieval**: Retrieve completed analysis results\n- **Error Handling**: Handle and recover from job failures\n- **Performance Monitoring**: Monitor job performance and timing\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Unique job identifier",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "in": "path",
            "name": "jobId",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/TaxAuditStatusResponse"
                }
              }
            },
            "description": "Job status retrieved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "message": {
                      "example": "Job not found",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Job not found"
          },
          "429": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "message": {
                      "example": "Too many status requests, please slow down",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Rate limit exceeded"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get tax audit analysis job status",
        "tags": [
          "AI Business Support"
        ]
      }
    },
    "/ai-config/models/grouped": {
      "get": {
        "description": "Retrieves all available AI models organized by their respective providers.\n      \n## Grouped Model Structure\n- **Provider Organization**: Models grouped by provider for easy navigation\n- **Complete Overview**: Single endpoint to get all providers and their models\n- **Structured Response**: Hierarchical data structure for frontend consumption\n- **Active Models Only**: Excludes inactive or deprecated models\n\n## Data Organization\n- **Provider Level**: Top-level grouping by provider name\n- **Model Details**: Each model includes ID, technical name, and display name\n- **Provider Context**: Models include provider ID for reference\n- **Consistent Structure**: Uniform data structure across all providers\n\n## Provider Coverage\n- **OpenAI Models**: GPT-4o, GPT-5 series with latest configurations\n- **Anthropic Models**: Claude 3.5, Claude 4 series including Sonnet, Opus, Haiku\n- **Google Models**: Gemini 1.5, 2.0, 2.5 series including Pro and Flash variants\n- **Together Models**: Open-source models including Llama, Mixtral, Qwen, DeepSeek\n- **OpenRouter Models**: Unified access to multiple providers through OpenRouter\n\n## Performance Optimization\n- **Single Query**: Efficient database query to retrieve all models\n- **Selective Fields**: Only retrieves necessary model information\n- **Grouped Processing**: Server-side grouping reduces client processing\n- **Caching Friendly**: Response structure optimized for client-side caching\n\n## Use Cases\n- **Model Overview**: Display all available models in organized interface\n- **Provider Comparison**: Compare models across different providers\n- **Configuration Dashboard**: Complete model configuration overview\n- **API Documentation**: Generate model availability documentation\n- **Frontend Initialization**: Bootstrap model selection components",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "grouped-models": {
                    "summary": "All models grouped by provider",
                    "value": {
                      "data": [
                        {
                          "models": [
                            {
                              "model_display_name": "GPT-5.2",
                              "model_name": "gpt-5.2",
                              "provider": 0
                            },
                            {
                              "model_display_name": "GPT-4o",
                              "model_name": "gpt-4o",
                              "provider": 0
                            }
                          ],
                          "provider": "OpenAI"
                        },
                        {
                          "models": [
                            {
                              "model_display_name": "Claude 4 Sonnet",
                              "model_name": "claude-sonnet-4-20250514",
                              "provider": 1
                            },
                            {
                              "model_display_name": "Claude 3.5 Sonnet",
                              "model_name": "claude-3-5-sonnet-20241022",
                              "provider": 1
                            }
                          ],
                          "provider": "Anthropic"
                        },
                        {
                          "models": [
                            {
                              "model_display_name": "Gemini 2.5 Pro",
                              "model_name": "gemini-2.5-pro",
                              "provider": 3
                            },
                            {
                              "model_display_name": "Gemini 1.5 Pro",
                              "model_name": "gemini-1.5-pro",
                              "provider": 3
                            }
                          ],
                          "provider": "Google"
                        }
                      ],
                      "message": "Grouped models retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/GroupedModelsResponse"
                }
              }
            },
            "description": "Grouped models retrieved successfully"
          },
          "401": {
            "content": {
              "application/json": {
                "examples": {
                  "authentication-required": {
                    "summary": "Authentication required",
                    "value": {
                      "error": "Unauthorized",
                      "message": "Authentication required to access AI model configuration",
                      "statusCode": 401
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Authentication required"
          },
          "500": {
            "content": {
              "application/json": {
                "examples": {
                  "database-error": {
                    "summary": "Database query error",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "Failed to retrieve grouped models from database",
                      "statusCode": 500
                    }
                  },
                  "grouping-error": {
                    "summary": "Model grouping error",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "Failed to group models by provider",
                      "statusCode": 500
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get all models grouped by provider",
        "tags": [
          "AI Configuration"
        ]
      }
    },
    "/ai-config/models/{provider}": {
      "get": {
        "description": "Retrieves all available models for a specified AI provider.\n      \n## Model Retrieval\n- **Provider Filtering**: Returns models only for the specified provider\n- **Active Models**: Only includes models that are currently active\n- **Model Metadata**: Includes model ID, technical name, and display name\n- **Database Query**: Efficient database query with selective field retrieval\n\n## Model Information\n- **Model ID**: Unique identifier for model configuration\n- **Technical Name**: API identifier used for model calls (e.g., 'gpt-4o')\n- **Display Name**: User-friendly name for UI display (e.g., 'GPT-4o')\n- **Provider Context**: Models filtered by specific provider\n\n## Provider Types\n- **0 - OpenAI**: GPT models including latest GPT-5 series\n- **1 - Anthropic**: Claude models including Sonnet, Opus, Haiku variants\n- **2 - Together**: Open-source models like Llama, Mixtral, Qwen\n- **3 - Google**: Gemini models including Pro, Flash variants\n- **4 - OpenRouter**: Unified access models from multiple providers\n\n## Performance Features\n- **Selective Queries**: Only retrieves necessary model fields\n- **Active Filtering**: Excludes inactive or deprecated models\n- **Optimized Response**: Minimal data transfer for frontend efficiency\n- **Caching Friendly**: Response structure suitable for client caching\n\n## Use Cases\n- **Model Selection**: Populate model dropdowns for specific providers\n- **Configuration UI**: Display available models for provider setup\n- **API Integration**: Get model identifiers for API calls\n- **Feature Management**: Check model availability for specific providers",
        "parameters": [
          {
            "description": "AI Provider ID (0=OpenAI, 1=Anthropic, 2=Together, 3=Google, 4=OpenRouter)",
            "in": "path",
            "name": "provider",
            "required": true,
            "schema": {
              "enum": [
                0,
                1,
                2,
                3,
                4
              ],
              "example": 0,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "anthropic-models": {
                    "summary": "Anthropic models retrieval",
                    "value": {
                      "data": [
                        {
                          "id": "550e8400-e29b-41d4-a716-446655440002",
                          "model_display_name": "Claude 4 Sonnet",
                          "model_name": "claude-sonnet-4-20250514"
                        },
                        {
                          "id": "550e8400-e29b-41d4-a716-446655440003",
                          "model_display_name": "Claude 3.5 Sonnet",
                          "model_name": "claude-3-5-sonnet-20241022"
                        }
                      ],
                      "message": "Models retrieved successfully",
                      "statusCode": 200
                    }
                  },
                  "openai-models": {
                    "summary": "OpenAI models retrieval",
                    "value": {
                      "data": [
                        {
                          "id": "550e8400-e29b-41d4-a716-446655440000",
                          "model_display_name": "GPT-5.2",
                          "model_name": "gpt-5.2"
                        },
                        {
                          "id": "550e8400-e29b-41d4-a716-446655440001",
                          "model_display_name": "GPT-4o",
                          "model_name": "gpt-4o"
                        }
                      ],
                      "message": "Models retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ModelsResponse"
                }
              }
            },
            "description": "Models retrieved successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "examples": {
                  "invalid-provider": {
                    "summary": "Invalid provider ID",
                    "value": {
                      "error": "Bad Request",
                      "message": "Invalid provider ID. Must be 0-4 (OpenAI, Anthropic, Together, Google, OpenRouter)",
                      "statusCode": 400
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Invalid provider ID"
          },
          "401": {
            "content": {
              "application/json": {
                "examples": {
                  "authentication-required": {
                    "summary": "Authentication required",
                    "value": {
                      "error": "Unauthorized",
                      "message": "Authentication required to access AI models",
                      "statusCode": 401
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Authentication required"
          },
          "404": {
            "content": {
              "application/json": {
                "examples": {
                  "no-models-found": {
                    "summary": "No models found",
                    "value": {
                      "error": "Not Found",
                      "message": "No active models found for the specified provider",
                      "statusCode": 404
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "No models found for provider"
          },
          "500": {
            "content": {
              "application/json": {
                "examples": {
                  "database-error": {
                    "summary": "Database query error",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "Failed to retrieve models from database",
                      "statusCode": 500
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get models for a specific AI provider",
        "tags": [
          "AI Configuration"
        ]
      }
    },
    "/ai-config/providers": {
      "get": {
        "description": "Retrieves a list of all available AI providers configured in the system.\n      \n## Provider Management\n- **Provider Enumeration**: Returns all configured AI providers from the system\n- **Active Providers**: Only includes providers that are currently active and configured\n- **Provider Mapping**: Maps internal provider IDs to human-readable names\n- **System Configuration**: Reflects current system AI provider configuration\n\n## Supported Providers\n- **OpenAI**: GPT models including GPT-4o, GPT-5 series\n- **Anthropic**: Claude models including Claude 3.5, Claude 4 series\n- **Google**: Gemini models including Gemini 1.5, 2.0, 2.5 series\n- **Together**: Open-source models via Together.ai platform\n- **OpenRouter**: Unified access to multiple AI providers\n\n## Response Format\n- **Provider Names**: Returns human-readable provider names\n- **Consistent Ordering**: Providers returned in consistent order\n- **Frontend Integration**: Optimized for dropdown and selection components\n- **Caching**: Response suitable for client-side caching\n\n## Use Cases\n- **Model Selection UI**: Populate provider selection dropdowns\n- **Configuration Management**: Display available providers for setup\n- **Feature Detection**: Check which AI providers are available\n- **Admin Interface**: Provider management and configuration",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-providers-retrieval": {
                    "summary": "Successful providers retrieval",
                    "value": {
                      "data": [
                        "OpenAI",
                        "Anthropic",
                        "Google",
                        "Together",
                        "OpenRouter"
                      ],
                      "message": "AI providers retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ProvidersResponse"
                }
              }
            },
            "description": "AI providers retrieved successfully"
          },
          "401": {
            "content": {
              "application/json": {
                "examples": {
                  "authentication-required": {
                    "summary": "Authentication required",
                    "value": {
                      "error": "Unauthorized",
                      "message": "Authentication required to access AI configuration",
                      "statusCode": 401
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Authentication required"
          },
          "500": {
            "content": {
              "application/json": {
                "examples": {
                  "server-error": {
                    "summary": "Internal server error",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "Failed to retrieve AI providers",
                      "statusCode": 500
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get all available AI providers",
        "tags": [
          "AI Configuration"
        ]
      }
    },
    "/ai-decisions/admin/credit-grants": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "additionalProperties": false,
                "properties": {
                  "credits": {
                    "exclusiveMinimum": 0,
                    "maximum": 100000,
                    "type": "number"
                  },
                  "note": {
                    "maxLength": 500,
                    "type": "string"
                  },
                  "userId": {
                    "format": "uuid",
                    "type": "string"
                  }
                },
                "required": [
                  "userId",
                  "credits"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "additionalProperties": false,
                      "properties": {
                        "credits": {
                          "additionalProperties": false,
                          "properties": {
                            "allowanceRemaining": {
                              "type": "number"
                            },
                            "allowanceUsed": {
                              "type": "number"
                            },
                            "available": {
                              "description": "allowanceRemaining + balance, floored at 0",
                              "type": "number"
                            },
                            "balance": {
                              "description": "Persistent credits (grants, top-ups); may be slightly negative",
                              "type": "number"
                            },
                            "monthUsage": {
                              "additionalProperties": false,
                              "properties": {
                                "credits": {
                                  "type": "number"
                                },
                                "decisions": {
                                  "type": "integer"
                                }
                              },
                              "required": [
                                "decisions",
                                "credits"
                              ],
                              "type": "object"
                            },
                            "monthlyAllowance": {
                              "description": "Credits per month for the plan",
                              "type": "number"
                            },
                            "period": {
                              "description": "UTC month the allowance belongs to",
                              "example": "2026-10",
                              "type": "string"
                            },
                            "resetsAt": {
                              "format": "date-time",
                              "type": "string"
                            }
                          },
                          "required": [
                            "period",
                            "resetsAt",
                            "monthlyAllowance",
                            "allowanceUsed",
                            "allowanceRemaining",
                            "balance",
                            "available",
                            "monthUsage"
                          ],
                          "type": "object"
                        },
                        "userId": {
                          "format": "uuid",
                          "type": "string"
                        }
                      },
                      "required": [
                        "userId",
                        "credits"
                      ],
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Granted; the user’s new balance"
          },
          "400": {
            "description": "Validation error"
          },
          "401": {
            "description": "Unauthorized"
          },
          "403": {
            "description": "管理者権限が必要です"
          },
          "404": {
            "description": "User not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Admin: add AI credits to a user",
        "tags": [
          "AI Decisions"
        ]
      }
    },
    "/ai-decisions/settings": {
      "put": {
        "description": "Does not change the chat provider, model or keys. 403 without key access.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "additionalProperties": false,
                "properties": {
                  "decisionEngine": {
                    "enum": [
                      "jev",
                      "llm"
                    ],
                    "type": "string"
                  }
                },
                "required": [
                  "decisionEngine"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "additionalProperties": false,
                      "properties": {
                        "creditUnitJpy": {
                          "description": "Yen per credit",
                          "type": "number"
                        },
                        "credits": {
                          "additionalProperties": false,
                          "description": "Platform-key users only; null otherwise (the credit system is dormant)",
                          "nullable": true,
                          "properties": {
                            "allowanceRemaining": {
                              "type": "number"
                            },
                            "allowanceUsed": {
                              "type": "number"
                            },
                            "available": {
                              "description": "allowanceRemaining + balance, floored at 0",
                              "type": "number"
                            },
                            "balance": {
                              "description": "Persistent credits (grants, top-ups); may be slightly negative",
                              "type": "number"
                            },
                            "monthUsage": {
                              "additionalProperties": false,
                              "properties": {
                                "credits": {
                                  "type": "number"
                                },
                                "decisions": {
                                  "type": "integer"
                                }
                              },
                              "required": [
                                "decisions",
                                "credits"
                              ],
                              "type": "object"
                            },
                            "monthlyAllowance": {
                              "description": "Credits per month for the plan",
                              "type": "number"
                            },
                            "period": {
                              "description": "UTC month the allowance belongs to",
                              "example": "2026-10",
                              "type": "string"
                            },
                            "resetsAt": {
                              "format": "date-time",
                              "type": "string"
                            }
                          },
                          "required": [
                            "period",
                            "resetsAt",
                            "monthlyAllowance",
                            "allowanceUsed",
                            "allowanceRemaining",
                            "balance",
                            "available",
                            "monthUsage"
                          ],
                          "type": "object"
                        },
                        "engine": {
                          "additionalProperties": false,
                          "properties": {
                            "access": {
                              "description": "platform = in JEV_PLATFORM_ALLOWED_USER_IDS (metered); byok = own OpenRouter key (unmetered); none = LLM only",
                              "enum": [
                                "platform",
                                "byok",
                                "none"
                              ],
                              "type": "string"
                            },
                            "decisions": {
                              "items": {
                                "additionalProperties": false,
                                "properties": {
                                  "defaultOn": {
                                    "description": "Jev answers this decision by default (passed the eval)",
                                    "type": "boolean"
                                  },
                                  "kind": {
                                    "enum": [
                                      "bank_transaction_category",
                                      "expense_category"
                                    ],
                                    "type": "string"
                                  },
                                  "label": {
                                    "type": "string"
                                  },
                                  "threshold": {
                                    "description": "Minimum probability; below it the LLM answers",
                                    "type": "number"
                                  }
                                },
                                "required": [
                                  "kind",
                                  "label",
                                  "defaultOn",
                                  "threshold"
                                ],
                                "type": "object"
                              },
                              "type": "array"
                            },
                            "enabledForUser": {
                              "description": "Switched on globally and the user has key access. False → the LLM path, no card, no credits.",
                              "type": "boolean"
                            },
                            "globallyEnabled": {
                              "description": "false when JEV_DECISIONS_ENABLED=0",
                              "type": "boolean"
                            },
                            "model": {
                              "example": "typesafe/jev-1.13",
                              "type": "string"
                            },
                            "setting": {
                              "description": "The user's 設定→AI choice ('llm' outside the rollout)",
                              "enum": [
                                "jev",
                                "llm"
                              ],
                              "type": "string"
                            }
                          },
                          "required": [
                            "enabledForUser",
                            "access",
                            "globallyEnabled",
                            "setting",
                            "model",
                            "decisions"
                          ],
                          "type": "object"
                        }
                      },
                      "required": [
                        "engine",
                        "credits",
                        "creditUnitJpy"
                      ],
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Saved; the new status"
          },
          "400": {
            "description": "Validation error"
          },
          "401": {
            "description": "Unauthorized"
          },
          "403": {
            "description": "No key access (not allowlisted, no own OpenRouter key)"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Set the decision engine (Jev / LLM only) — users with key access only",
        "tags": [
          "AI Decisions"
        ]
      }
    },
    "/ai-decisions/status": {
      "get": {
        "description": "Whether Jev is on for the caller and with which key, which decisions it answers by default, and — for platform-key users only — the monthly allowance and balance. Not cached.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "additionalProperties": false,
                      "properties": {
                        "creditUnitJpy": {
                          "description": "Yen per credit",
                          "type": "number"
                        },
                        "credits": {
                          "additionalProperties": false,
                          "description": "Platform-key users only; null otherwise (the credit system is dormant)",
                          "nullable": true,
                          "properties": {
                            "allowanceRemaining": {
                              "type": "number"
                            },
                            "allowanceUsed": {
                              "type": "number"
                            },
                            "available": {
                              "description": "allowanceRemaining + balance, floored at 0",
                              "type": "number"
                            },
                            "balance": {
                              "description": "Persistent credits (grants, top-ups); may be slightly negative",
                              "type": "number"
                            },
                            "monthUsage": {
                              "additionalProperties": false,
                              "properties": {
                                "credits": {
                                  "type": "number"
                                },
                                "decisions": {
                                  "type": "integer"
                                }
                              },
                              "required": [
                                "decisions",
                                "credits"
                              ],
                              "type": "object"
                            },
                            "monthlyAllowance": {
                              "description": "Credits per month for the plan",
                              "type": "number"
                            },
                            "period": {
                              "description": "UTC month the allowance belongs to",
                              "example": "2026-10",
                              "type": "string"
                            },
                            "resetsAt": {
                              "format": "date-time",
                              "type": "string"
                            }
                          },
                          "required": [
                            "period",
                            "resetsAt",
                            "monthlyAllowance",
                            "allowanceUsed",
                            "allowanceRemaining",
                            "balance",
                            "available",
                            "monthUsage"
                          ],
                          "type": "object"
                        },
                        "engine": {
                          "additionalProperties": false,
                          "properties": {
                            "access": {
                              "description": "platform = in JEV_PLATFORM_ALLOWED_USER_IDS (metered); byok = own OpenRouter key (unmetered); none = LLM only",
                              "enum": [
                                "platform",
                                "byok",
                                "none"
                              ],
                              "type": "string"
                            },
                            "decisions": {
                              "items": {
                                "additionalProperties": false,
                                "properties": {
                                  "defaultOn": {
                                    "description": "Jev answers this decision by default (passed the eval)",
                                    "type": "boolean"
                                  },
                                  "kind": {
                                    "enum": [
                                      "bank_transaction_category",
                                      "expense_category"
                                    ],
                                    "type": "string"
                                  },
                                  "label": {
                                    "type": "string"
                                  },
                                  "threshold": {
                                    "description": "Minimum probability; below it the LLM answers",
                                    "type": "number"
                                  }
                                },
                                "required": [
                                  "kind",
                                  "label",
                                  "defaultOn",
                                  "threshold"
                                ],
                                "type": "object"
                              },
                              "type": "array"
                            },
                            "enabledForUser": {
                              "description": "Switched on globally and the user has key access. False → the LLM path, no card, no credits.",
                              "type": "boolean"
                            },
                            "globallyEnabled": {
                              "description": "false when JEV_DECISIONS_ENABLED=0",
                              "type": "boolean"
                            },
                            "model": {
                              "example": "typesafe/jev-1.13",
                              "type": "string"
                            },
                            "setting": {
                              "description": "The user's 設定→AI choice ('llm' outside the rollout)",
                              "enum": [
                                "jev",
                                "llm"
                              ],
                              "type": "string"
                            }
                          },
                          "required": [
                            "enabledForUser",
                            "access",
                            "globallyEnabled",
                            "setting",
                            "model",
                            "decisions"
                          ],
                          "type": "object"
                        }
                      },
                      "required": [
                        "engine",
                        "credits",
                        "creditUnitJpy"
                      ],
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Status"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Decision engine status and AI credit balance",
        "tags": [
          "AI Decisions"
        ]
      }
    },
    "/ai-reconciliation/batch-process": {
      "post": {
        "description": "Process multiple transactions in batch using AI with configurable automation options.\n\n## AI Batch Processing (AIバッチ処理) - v4.54 Parallel\n\nHigh-volume transaction processing with **~3x faster** parallel execution:\n- **Parallel Processing (v4.54)**: Concurrent AI calls with sliding window concurrency control (3 parallel)\n- **Auto-Retry**: Exponential backoff with jitter for failed requests (max 2 retries)\n- **Configurable Automation**: Flexible automation options with confidence thresholds\n- **Rule Application**: Applies existing automation rules with override options\n- **Quality Control**: Built-in quality control with confidence-based filtering\n- **Comprehensive Reporting**: Detailed results for each processed transaction\n\n## Processing Options\n- **Auto-Match**: Automatically match transactions with documents above confidence threshold\n- **Auto-Journalize**: Automatically generate journal entries for matched transactions\n- **Apply Rules**: Apply existing automation rules to qualifying transactions\n- **Confidence Threshold**: Set minimum confidence level for automated actions\n- **Manual Review**: Flag transactions requiring manual review\n\n## Parallel Processing Flow (v4.54)\n1. **Rules Pre-fetch**: Fetch reconciliation rules once (shared across all transactions)\n2. **Concurrent Execution**: Process up to 3 transactions simultaneously\n3. **Sliding Window**: As one completes, next one starts automatically\n4. **AI Analysis**: Applies AI categorization, matching, and rule suggestions\n5. **Retry Logic**: Failed items retry with exponential backoff (1s → 2s → 4s)\n6. **Result Compilation**: Compiles comprehensive results as they complete\n\n## Performance (v4.54)\n\n| Transactions | Before (Sequential) | After (Parallel) | Speedup |\n|--------------|---------------------|------------------|---------|\n| 5            | ~15s                | ~5s              | ~3x     |\n| 10           | ~30s                | ~10s             | ~3x     |\n| 20           | ~60s                | ~20s             | ~3x     |\n\n## Processing Results\n- **Status Classification**: Each transaction classified as matched, rule_applied, needs_review, or error\n- **Confidence Scores**: AI confidence scores for all automated actions\n- **Match Information**: Details about document matches and applied rules\n- **Journal Suggestions**: Generated journal entries for appropriate transactions\n- **Manual Review Flags**: Clear identification of transactions requiring human attention\n\n## Quality Control\n- **Confidence Thresholds**: Configurable minimum confidence levels for automation\n- **Risk Assessment**: Automatic risk assessment for each transaction\n- **Error Handling**: Graceful handling with individual retries (max 2 per transaction)\n- **Validation Checks**: Multiple validation layers to ensure data integrity\n- **Audit Trail**: Complete audit trail for all automated actions\n\n## Performance Optimization (v4.54)\n- **Sliding Window Concurrency**: 3 parallel requests (respects API rate limits)\n- **Exponential Backoff**: 1s base delay, 10s max, with jitter to prevent thundering herd\n- **Rules Pre-caching**: Fetch rules once, share across all transactions\n- **Error Recovery**: Per-transaction retry without blocking other transactions\n- **Resource Management**: Efficient resource usage with controlled concurrency\n\n## Rate Limiting\n- **Batch Operations**: Stricter limit of 10 requests per hour due to high API costs\n- **Cost Management**: Enhanced rate limiting to manage OpenAI API costs for batch operations\n- **Fair Usage**: Ensures fair access to batch processing resources\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/BatchProcessRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BatchProcessApiResponse"
                }
              }
            },
            "description": "Batch processing completed successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "message": {
                      "example": "Too many batch requests, please try again later",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Rate limit exceeded"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Process multiple transactions with AI assistance",
        "tags": [
          "AI Reconciliation"
        ]
      }
    },
    "/ai-reconciliation/categorize-transaction": {
      "post": {
        "description": "Automatically categorize a bank transaction using AI with company context analysis.\n\n## AI Transaction Categorization (AI取引分類)\nIntelligent transaction analysis with:\n- **Company Context Analysis**: Leverages company type, industry, and business patterns for accurate categorization\n- **Multi-Factor Analysis**: Analyzes transaction description, amount, date, and historical patterns\n- **Account Suggestions**: Provides multiple account code suggestions with confidence scores\n- **Tax Category Classification**: Determines appropriate tax categories for Japanese accounting\n- **Confidence Scoring**: All suggestions include confidence scores (0-1) for decision support\n\n## Categorization Process\n1. **Transaction Analysis**: AI analyzes transaction description, amount, and context\n2. **Company Context**: Incorporates company industry, type, and fiscal year information\n3. **Pattern Recognition**: Identifies patterns from similar historical transactions\n4. **Account Mapping**: Maps to appropriate chart of accounts with confidence scores\n5. **Tax Classification**: Determines tax treatment and categories\n6. **Reasoning**: Provides clear reasoning for categorization decisions\n\n## Company Context Integration\n- **Industry-Specific**: Categorization adapted to company's industry and business type\n- **Historical Learning**: Learns from company's transaction history and patterns\n- **Fiscal Year Awareness**: Considers fiscal year timing for seasonal adjustments\n- **Business Rules**: Applies business-specific rules and preferences\n\n## AI Features\n- **Natural Language Processing**: Advanced analysis of Japanese transaction descriptions\n- **Pattern Recognition**: Identifies recurring transaction patterns and vendors\n- **Confidence Assessment**: Provides confidence scores for all suggestions\n- **Multi-Option Suggestions**: Offers multiple account options with reasoning\n- **Continuous Learning**: Improves accuracy based on user feedback and corrections\n\n## Use Cases\n- **Automated Bookkeeping**: Reduce manual categorization effort\n- **Consistency**: Ensure consistent categorization across transactions\n- **Training**: Help train accounting staff on proper categorization\n- **Audit Trail**: Maintain clear reasoning for all categorization decisions\n- **Compliance**: Ensure proper tax category assignment for Japanese regulations\n\n## Rate Limiting\n- **AI Operations**: Limited to 30 requests per 15 minutes per user\n- **Cost Management**: Rate limiting to manage OpenAI API costs\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CategorizeTransactionRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CategorizeTransactionApiResponse"
                }
              }
            },
            "description": "Transaction categorized successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "message": {
                      "example": "Too many AI requests, please try again later",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Rate limit exceeded"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Categorize bank transaction using AI",
        "tags": [
          "AI Reconciliation"
        ]
      }
    },
    "/ai-reconciliation/generate-journal-entry": {
      "post": {
        "description": "Generate accurate journal entries from matched transactions and documents using AI.\n\n## AI Journal Entry Generation (AI仕訳生成)\nAutomated journal entry creation with:\n- **Japanese Accounting Standards**: Full compliance with Japanese accounting principles and standards\n- **Multi-Document Integration**: Incorporates transaction and document data for accurate entries\n- **Tax Category Assignment**: Proper tax category classification for Japanese tax compliance\n- **Expense Breakdown**: Handles complex expense breakdowns with multiple categories\n- **Validation Warnings**: Provides warnings and considerations for manual review\n\n## Generation Process\n1. **Data Integration**: Combines transaction and document information\n2. **Account Mapping**: Maps expenses to appropriate chart of accounts\n3. **Tax Analysis**: Determines correct tax categories and treatments\n4. **Entry Creation**: Generates balanced debit and credit entries\n5. **Validation**: Validates entry completeness and compliance\n6. **Documentation**: Links related documents and provides explanations\n\n## Journal Types Supported\n- **Reimbursement (経費精算)**: Employee expense reimbursements\n- **Income (収入)**: Revenue and income transactions\n- **Expense (支出)**: Direct business expenses\n- **Transfer (振替)**: Inter-account transfers\n- **Suspense (仮勘定)**: Temporary or unclear transactions\n\n## Japanese Accounting Compliance\n- **Chart of Accounts**: Uses standard Japanese account codes and classifications\n- **Tax Categories**: Proper classification for consumption tax and other Japanese taxes\n- **Documentation**: Maintains proper documentation links for audit trails\n- **Compliance Checks**: Validates entries against Japanese accounting standards\n- **Warning System**: Alerts for potential compliance issues or required manual review\n\n## AI Features\n- **Context Understanding**: Understands business context and transaction purpose\n- **Multi-Category Handling**: Properly splits expenses across multiple categories\n- **Tax Intelligence**: Intelligent tax category assignment based on expense type\n- **Explanation Generation**: Provides clear explanations for journal entry logic\n- **Warning Detection**: Identifies potential issues requiring manual attention\n\n## Validation and Warnings\n- **Balance Verification**: Ensures debit and credit amounts balance\n- **Account Validation**: Verifies account codes exist and are appropriate\n- **Tax Compliance**: Checks tax category assignments for compliance\n- **Documentation**: Warns about missing or incomplete documentation\n- **Amount Verification**: Validates amounts against source documents\n\n## Rate Limiting\n- **AI Operations**: Limited to 30 requests per 15 minutes per user\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/GenerateJournalEntryRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GenerateJournalEntryApiResponse"
                }
              }
            },
            "description": "Journal entry generated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "message": {
                      "example": "Too many AI requests, please try again later",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Rate limit exceeded"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Generate journal entry from transaction and document",
        "tags": [
          "AI Reconciliation"
        ]
      }
    },
    "/ai-reconciliation/generate-journal-entry-simple": {
      "post": {
        "description": "Generate journal entries using a simplified, frontend-friendly request format with comprehensive validation.\n\n## Simplified Journal Generation (簡易仕訳生成)\n\nThis endpoint provides a more flexible interface for journal entry generation:\n\n### Request Options\n\n**Option 1: Transaction ID**\n- Provide `transactionId` to fetch transaction data from database\n- Useful when working with existing bank transactions\n\n**Option 2: Inline Data**\n- Provide `description`, `amount`, `date` directly\n- Useful for preview or ad-hoc generation\n\n### Auto-Detection Features\n\n- **Journal Type**: If `journalType` is \"auto\" or not provided, AI will determine the best type\n- **Transaction Type**: Automatically detected from amount sign if not provided\n- **Bank Account**: Defaults to 普通預金 (1100) if not specified\n\n### Integration with Categorization\n\nPass results from `/categorize-transaction` for better accuracy:\n- `suggestedAccountCode`: Account code from categorization\n- `suggestedAccountName`: Account name from categorization\n- `taxCategory`: Tax category from categorization\n\n### Response Enhancements (v4.29)\n\n- `suggestedJournalType`: AI's recommended journal type\n- `confidence`: Confidence score (0-1)\n- `appliedPreferences`: User preferences that influenced the result\n- `validation`: **NEW** - Comprehensive validation results with error details\n- `transactionAnalysis`: **NEW** - Counterparty detection and suggested accounts\n- `correctedEntries`: **NEW** - Auto-corrected entries when validation fails\n\n### Journal Entry Validation (v4.29) - 仕訳検証\n\nAutomatic validation against Japanese double-entry bookkeeping rules:\n\n| Rule | Description |\n|------|-------------|\n| **Debit/Credit Balance** | 借方合計 = 貸方合計 (±1円許容) |\n| **Bank Account Side** | 入金: 借方=普通預金, 出金: 貸方=普通預金 |\n| **Both Sides Check** | 両方が普通預金のみは禁止（振替除く） |\n| **Amount Validation** | 全金額が正の整数 |\n\n### Counterparty Detection (v4.29) - 取引先検出\n\nAI detects counterparty type from description:\n- **Company** (株式会社, （カ, etc.): Suggests 売上高/売掛金\n- **Bank** (利息, 銀行, etc.): Suggests 受取利息\n- **Government** (税務署, etc.): Suggests 租税公課\n- **Individual**: Suggests 仮受金 for review\n\n### Auto-Correction (v4.29) - 自動修正\n\nWhen validation fails, the system suggests corrected entries:\n- Invalid deposit (両方普通預金) → Suggests 売上高 or 仮受金 for credit\n- Invalid withdrawal (両方普通預金) → Suggests 仮払金 for debit\n\n### Japanese Accounting Support\n\nFull support for Japanese accounting standards including:\n- 一人社長向け特有の仕訳パターン（役員借入金、役員貸付金）\n- 消費税区分の自動判定\n- 源泉徴収の考慮\n- 立替経費精算の正しい処理\n- 仮勘定（仮受金、仮払金）の適切な使用\n\n### Supported Journal Patterns\n\n| Transaction | Debit | Credit | Example |\n|-------------|-------|--------|---------|\n| 売上入金 | 普通預金 | 売上高/売掛金 | 取引先からの入金 |\n| 経費支払 | 経費科目 | 普通預金 | クラウドサービス利用料 |\n| 立替精算 | 未払金 | 普通預金 | 従業員への経費精算 |\n| 利息入金 | 普通預金 | 受取利息 | 銀行口座利息 |\n| 口座振替 | 普通預金A | 普通預金B | 銀行間資金移動 |\n\n## Rate Limiting\n- **AI Operations**: Limited to 30 requests per 15 minutes per user\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "inlineData": {
                  "summary": "With inline data",
                  "value": {
                    "amount": -12345,
                    "date": "2026-01-15",
                    "description": "AWS利用料金",
                    "journalType": "auto",
                    "transactionType": "withdrawal"
                  }
                },
                "withContext": {
                  "summary": "With company context",
                  "value": {
                    "context": {
                      "companyName": "サンプル合同会社",
                      "companyType": "合同会社",
                      "industry": "IT/ソフトウェア"
                    },
                    "journalType": "auto",
                    "transactionId": "f47ac10b-58cc-4372-a567-0e02b2c3d479"
                  }
                },
                "withTransactionId": {
                  "summary": "Using transaction ID",
                  "value": {
                    "journalType": "expense",
                    "suggestedAccountCode": "5120",
                    "suggestedAccountName": "通信費",
                    "transactionId": "f47ac10b-58cc-4372-a567-0e02b2c3d479"
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/GenerateJournalEntrySimpleRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GenerateJournalEntrySimpleResponse"
                }
              }
            },
            "description": "Journal entry generated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "message": {
                      "example": "Transaction not found",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Transaction not found"
          },
          "429": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "message": {
                      "example": "Too many AI requests, please try again later",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Rate limit exceeded"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Generate journal entry with simplified request (v4.29)",
        "tags": [
          "AI Reconciliation"
        ]
      }
    },
    "/ai-reconciliation/match-documents": {
      "post": {
        "description": "Intelligently match bank transactions with expense documents using AI analysis.\n\n## AI Document Matching (AI文書マッチング)\nAdvanced document matching with:\n- **Multi-Document Support**: Matches against expense claims, invoices, receipts, and travel expenses\n- **Smart Search Scope**: Configurable date ranges and document type filtering\n- **Split Matching**: Handles complex scenarios where one transaction matches multiple documents\n- **Confidence Scoring**: Provides match confidence scores for all suggestions\n- **Action Recommendations**: Suggests appropriate actions (link, reconcile, review)\n\n## Matching Process\n1. **Transaction Analysis**: Analyzes transaction amount, date, and description\n2. **Document Search**: Searches relevant documents within specified scope\n3. **AI Matching**: Uses AI to identify potential matches based on multiple factors\n4. **Score Calculation**: Calculates confidence scores for each potential match\n5. **Split Detection**: Identifies scenarios where multiple documents sum to transaction amount\n6. **Action Suggestion**: Recommends appropriate next steps for each match\n\n## Matching Criteria\n- **Amount Matching**: Exact and approximate amount matching with tolerance\n- **Date Proximity**: Considers transaction and document dates with configurable ranges\n- **Description Analysis**: AI analysis of transaction and document descriptions\n- **Vendor Recognition**: Matches vendor names and payment recipients\n- **Pattern Recognition**: Identifies recurring payment patterns and relationships\n\n## Match Types\n- **Single Match**: One document matches the transaction perfectly\n- **Split Match**: Multiple documents combine to match the transaction amount\n- **No Match**: No suitable documents found with explanation\n- **Alternative Matches**: Multiple potential matches with different confidence levels\n\n## Document Types Supported\n- **Expense Claims (経費精算書)**: Employee expense reimbursement requests\n- **Travel Expenses (出張費)**: Business travel expense reports\n- **Invoices (請求書)**: Vendor invoices and bills\n- **Receipts (領収書)**: Purchase receipts and proof of payment\n\n## Search Optimization\n- **Date Range Intelligence**: Automatic date range adjustment based on document type\n- **Document Type Filtering**: Focus search on relevant document types\n- **Performance Optimization**: Efficient search algorithms for large document volumes\n- **Relevance Ranking**: AI-powered relevance ranking for match results\n\n## Rate Limiting\n- **AI Operations**: Limited to 30 requests per 15 minutes per user\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/MatchDocumentsRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MatchDocumentsApiResponse"
                }
              }
            },
            "description": "Documents matched successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "message": {
                      "example": "Too many AI requests, please try again later",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Rate limit exceeded"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Find matching documents for bank transaction",
        "tags": [
          "AI Reconciliation"
        ]
      }
    },
    "/ai-reconciliation/suggest-rules": {
      "post": {
        "description": "Generate intelligent automation rules based on historical transaction patterns.\n\n## AI Rule Suggestion (AIルール提案)\nSmart automation rule generation with:\n- **Pattern Analysis**: Analyzes historical transaction patterns to identify automation opportunities\n- **Rule Optimization**: Suggests rules that maximize automation while maintaining accuracy\n- **Conflict Detection**: Identifies and avoids conflicts with existing automation rules\n- **Confidence Assessment**: Provides confidence scores for each suggested rule\n- **Priority Ranking**: Ranks rules by potential impact and reliability\n\n## Analysis Process\n1. **Transaction History Analysis**: Examines patterns in transaction descriptions, amounts, and timing\n2. **Frequency Detection**: Identifies recurring transactions suitable for automation\n3. **Pattern Recognition**: Recognizes vendor patterns, amount ranges, and categorization consistency\n4. **Rule Generation**: Creates automation rules with appropriate conditions and actions\n5. **Conflict Resolution**: Ensures new rules don't conflict with existing automation\n6. **Priority Assignment**: Ranks rules by automation potential and confidence\n\n## Rule Components\n- **Conditions**: Description patterns, amount ranges, transaction types, frequency patterns\n- **Actions**: Category assignment, account mapping, tax classification, automation settings\n- **Confidence Scoring**: AI-generated confidence scores for rule reliability\n- **Priority Ranking**: Importance ranking based on transaction volume and accuracy potential\n- **Reasoning**: Clear explanations for why each rule is suggested\n\n## Automation Options\n- **Auto-Reconcile**: Automatically reconcile transactions matching rule conditions\n- **Auto-Journalize**: Automatically generate journal entries for matched transactions\n- **Category Assignment**: Automatically assign categories and account codes\n- **Tax Classification**: Automatically determine tax categories and treatments\n- **Review Flags**: Flag transactions for manual review based on risk assessment\n\n## Pattern Recognition\n- **Vendor Patterns**: Recognizes recurring vendors and payment recipients\n- **Amount Patterns**: Identifies consistent amount ranges and payment frequencies\n- **Description Patterns**: Analyzes transaction description patterns and keywords\n- **Timing Patterns**: Recognizes monthly, quarterly, or annual payment patterns\n- **Category Consistency**: Identifies transactions consistently categorized the same way\n\n## Risk Assessment\n- **Automation Safety**: Assesses safety of automating each identified pattern\n- **Error Potential**: Evaluates potential for categorization errors\n- **Review Requirements**: Identifies transactions that should always require manual review\n- **Confidence Thresholds**: Suggests appropriate confidence thresholds for automation\n- **Fallback Procedures**: Recommends fallback procedures for edge cases\n\n## Rate Limiting\n- **AI Operations**: Limited to 30 requests per 15 minutes per user\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/SuggestRulesRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SuggestRulesApiResponse"
                }
              }
            },
            "description": "Rules suggested successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "message": {
                      "example": "Too many AI requests, please try again later",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Rate limit exceeded"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Suggest automation rules based on transaction patterns",
        "tags": [
          "AI Reconciliation"
        ]
      }
    },
    "/ai-service/analyze-batch": {
      "post": {
        "description": "Analyze multiple documents in batch with real-time SSE progress updates.\n\n## Batch Document Analysis (証憑一括解析)\nProcess multiple files (uploaded or from URLs) with AI-powered analysis. Progress is streamed via SSE.\n\n## Supported File Types\n- **Images**: JPEG, PNG (receipts, invoices, documents)\n- **Documents**: PDF (invoices, contracts, statements)\n\n## Analysis Features\n- Automatic text extraction (OCR for images)\n- Structured data extraction (vendor, amount, date, items)\n- Multi-file parallel processing (3 concurrent)\n- Maximum 20 files per batch\n\n## Workflow\n1. Connect to SSE endpoint first: `GET /analyze/connect?session_id=xxx`\n2. Submit batch: `POST /analyze-batch` with same session_id\n3. Receive progress events via SSE\n4. Handle completion event with all results\n\n## Request Format\n- **session_id**: Required. Must match SSE connection session\n- **files**: Optional. Direct file uploads (multipart/form-data)\n- **file_urls**: Optional. JSON array of `{name, url}` for URL-based files\n- **prompt**: Optional. Custom analysis prompt",
        "requestBody": {
          "content": {
            "multipart/form-data": {
              "schema": {
                "properties": {
                  "file_urls": {
                    "description": "JSON array of {name, url} for URL-based files",
                    "example": "[{\"name\":\"receipt.jpg\",\"url\":\"https://...\"}]",
                    "type": "string"
                  },
                  "files": {
                    "description": "Files to analyze (max 20, max 2MB each)",
                    "items": {
                      "format": "binary",
                      "type": "string"
                    },
                    "type": "array"
                  },
                  "prompt": {
                    "description": "Custom analysis prompt (optional)",
                    "example": "Extract vendor name, date, and total amount",
                    "type": "string"
                  },
                  "session_id": {
                    "description": "Session ID matching SSE connection",
                    "example": "analysis_1234567890_abc123",
                    "type": "string"
                  }
                },
                "required": [
                  "session_id"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "sessionId": {
                          "example": "analysis_1234567890_abc123",
                          "type": "string"
                        },
                        "totalFiles": {
                          "example": 3,
                          "type": "number"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Batch analysis completed",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Batch analysis completed"
          },
          "400": {
            "content": {
              "application/json": {
                "examples": {
                  "noFiles": {
                    "summary": "No files provided",
                    "value": {
                      "error": "No files provided for analysis"
                    }
                  },
                  "tooManyFiles": {
                    "summary": "Too many files",
                    "value": {
                      "error": "Maximum 20 files allowed per batch"
                    }
                  }
                }
              }
            },
            "description": "Invalid request"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Batch document analysis with SSE progress (v4.21)",
        "tags": [
          "AI Service"
        ]
      }
    },
    "/ai-service/analyze-image": {
      "post": {
        "description": "Analyzes uploaded images using a unified AI service that automatically routes to the appropriate provider based on user configuration.\n      \n## Unified AI Provider Support\n- **OpenAI**: GPT-4o, GPT-4o-mini, GPT-4-turbo models for advanced image analysis\n- **Google Gemini**: Gemini 1.5 Flash and Pro models for fast and detailed analysis\n- **Anthropic Claude**: Claude 3.5 Sonnet and Haiku for sophisticated image understanding\n- **Automatic Routing**: Intelligently selects provider based on user AI settings\n\n## Image Analysis Capabilities\n- **Content Recognition**: Identifies objects, people, text, and scenes in images\n- **Text Extraction**: Reads and transcribes text content from images (OCR)\n- **Scene Description**: Provides detailed descriptions of image content and context\n- **Custom Prompts**: Allows specific questions or analysis requests about the image\n- **Multi-Provider**: Consistent interface across different AI providers\n\n## File Upload Requirements\n- **Supported Formats**: JPEG, JPG, PNG\n- **Maximum Size**: 2MB per image\n- **Storage**: Temporary memory storage for processing\n- **Validation**: Automatic file type and size validation\n\n## Provider Selection Logic\n- **User Configuration**: Uses user's preferred AI provider and API key\n- **Fallback System**: Falls back to system API keys when user keys unavailable\n- **Model Selection**: Supports provider-specific model selection\n- **Performance Optimization**: Routes to fastest available provider when possible\n\n## Security and Authentication\n- **Bearer Token Required**: Requires valid JWT authentication\n- **Demo Guard Protection**: Additional protection for demo environments\n- **User Context**: Analysis tied to authenticated user for tracking\n- **File Validation**: Comprehensive validation of uploaded files\n- **API Key Management**: Secure handling of user and system API keys\n\n## Use Cases\n- **Document Analysis**: Extract text and analyze document content across providers\n- **Product Recognition**: Identify products, brands, or items using best available AI\n- **Scene Understanding**: Understand context and details with provider-specific strengths\n- **Accessibility**: Generate descriptions optimized by different AI capabilities\n- **Content Moderation**: Analyze image content using multiple AI perspectives",
        "requestBody": {
          "content": {
            "multipart/form-data": {
              "examples": {
                "auto-provider-selection": {
                  "summary": "Use user-configured provider",
                  "value": {
                    "prompt": "Analyze this image and tell me what you see"
                  }
                },
                "claude-scene-description": {
                  "summary": "Describe scene with Claude",
                  "value": {
                    "max_tokens": 500,
                    "model": "claude-3-5-sonnet-20241022",
                    "prompt": "Describe this image in detail, including the setting, objects, and atmosphere"
                  }
                },
                "gemini-product-identification": {
                  "summary": "Identify products with Gemini",
                  "value": {
                    "model": "gemini-1.5-flash",
                    "prompt": "What products can you see in this image? List them with descriptions."
                  }
                },
                "openai-document-analysis": {
                  "summary": "Analyze document with OpenAI",
                  "value": {
                    "max_tokens": 1000,
                    "model": "gpt-4o",
                    "prompt": "Extract all text from this document and summarize its content"
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/AIImageAnalysisRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-gemini-analysis": {
                    "summary": "Successful Gemini analysis",
                    "value": {
                      "data": {
                        "analysis": "The image depicts a clean, minimalist workspace featuring a silver laptop, white ceramic mug, and bound notebook arranged on a light wooden surface. Natural lighting creates a warm, productive atmosphere.",
                        "metadata": {
                          "apiKeySource": "system_key",
                          "imageSize": 1048576,
                          "mimeType": "image/jpeg",
                          "processingTime": 1890
                        },
                        "model": "gemini-1.5-flash",
                        "provider": "gemini",
                        "usage": {
                          "completionTokens": 142,
                          "promptTokens": 25,
                          "totalTokens": 167
                        }
                      },
                      "message": "Image analyzed successfully",
                      "statusCode": 200
                    }
                  },
                  "successful-openai-analysis": {
                    "summary": "Successful OpenAI analysis",
                    "value": {
                      "data": {
                        "analysis": "This image shows a modern office workspace with a laptop computer, a white coffee mug, and a spiral notebook on a wooden desk. The laptop screen displays what appears to be code or text. The lighting is natural daylight coming from a window on the left side of the frame.",
                        "metadata": {
                          "apiKeySource": "user_key",
                          "imageSize": 1048576,
                          "mimeType": "image/jpeg",
                          "processingTime": 2340
                        },
                        "model": "gpt-4o",
                        "provider": "openai",
                        "usage": {
                          "completionTokens": 156,
                          "promptTokens": 28,
                          "totalTokens": 184
                        }
                      },
                      "message": "Image analyzed successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/AIImageAnalysisResponse"
                }
              }
            },
            "description": "Image analysis completed successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "examples": {
                  "file-too-large": {
                    "summary": "File exceeds size limit",
                    "value": {
                      "error": "Bad Request",
                      "message": "File too large. Maximum size is 2MB.",
                      "statusCode": 400
                    }
                  },
                  "invalid-file-type": {
                    "summary": "Invalid file type uploaded",
                    "value": {
                      "error": "Bad Request",
                      "message": "Invalid file type: image/gif. Only JPEG, PNG are supported.",
                      "statusCode": 400
                    }
                  },
                  "invalid-provider": {
                    "summary": "Invalid AI provider configuration",
                    "value": {
                      "error": "Bad Request",
                      "message": "Invalid provider",
                      "statusCode": 400
                    }
                  },
                  "no-api-key": {
                    "summary": "No API key available for selected provider",
                    "value": {
                      "error": "Bad Request",
                      "message": "No OpenAI API key available",
                      "statusCode": 400
                    }
                  },
                  "no-file-provided": {
                    "summary": "No image file provided",
                    "value": {
                      "error": "Bad Request",
                      "message": "No file provided",
                      "statusCode": 400
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Invalid request or file validation error"
          },
          "401": {
            "content": {
              "application/json": {
                "examples": {
                  "invalid-token": {
                    "summary": "Invalid or expired JWT token",
                    "value": {
                      "error": "Unauthorized",
                      "message": "Invalid or expired authentication token",
                      "statusCode": 401
                    }
                  },
                  "missing-token": {
                    "summary": "Missing Authorization header",
                    "value": {
                      "error": "Unauthorized",
                      "message": "Authorization header is required",
                      "statusCode": 401
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Authentication required or invalid token"
          },
          "403": {
            "content": {
              "application/json": {
                "examples": {
                  "demo-restricted": {
                    "summary": "Demo user access restricted",
                    "value": {
                      "error": "Forbidden",
                      "message": "Demo users cannot access this feature",
                      "statusCode": 403
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Demo access restricted"
          },
          "413": {
            "content": {
              "application/json": {
                "examples": {
                  "file-too-large": {
                    "summary": "File exceeds 2MB limit",
                    "value": {
                      "error": "Payload Too Large",
                      "message": "File size exceeds the 2MB limit",
                      "statusCode": 413
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "File size exceeds limit"
          },
          "429": {
            "content": {
              "application/json": {
                "examples": {
                  "rate-limit": {
                    "summary": "API rate limit exceeded",
                    "value": {
                      "error": "Too Many Requests",
                      "message": "Rate limit exceeded. Please try again later.",
                      "statusCode": 429
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Rate limit exceeded"
          },
          "500": {
            "content": {
              "application/json": {
                "examples": {
                  "ai-service-error": {
                    "summary": "AI service error",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "Failed to analyze image with AI service",
                      "statusCode": 500
                    }
                  },
                  "processing-error": {
                    "summary": "Image processing error",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "Failed to process uploaded image",
                      "statusCode": 500
                    }
                  },
                  "provider-error": {
                    "summary": "AI provider API error",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "AI provider API returned an error",
                      "statusCode": 500
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error or AI service error"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Analyze image content using unified AI service",
        "tags": [
          "AI Service"
        ]
      }
    },
    "/ai-service/analyze-pdf": {
      "post": {
        "description": "Analyzes PDF documents using AI-powered text extraction and content analysis. Currently supports OpenAI models for comprehensive document understanding.\n      \n## PDF Analysis Capabilities\n- **Document Text Extraction**: Extracts and processes text content from PDF files\n- **Content Analysis**: Analyzes document structure, key information, and themes\n- **Information Extraction**: Identifies and extracts specific data points and insights\n- **Document Summarization**: Creates concise summaries of document content\n- **Custom Analysis**: Supports custom prompts for specific analysis requirements\n\n## AI Provider Support\n- **OpenAI**: GPT-4o and GPT-5 series models for advanced document analysis\n- **Automatic Processing**: Uses OpenAI's Responses API with input_file support\n- **High Accuracy**: Leverages latest AI models for precise text understanding\n\n## Document Processing Features\n- **Base64 Input**: Accepts PDF files as base64 encoded strings\n- **Filename Context**: Uses original filename for better analysis context\n- **Token Management**: Configurable max_tokens for response length control\n- **Structured Output**: Returns analysis in structured, readable format\n\n## File Upload Requirements\n- **Supported Formats**: PDF documents only\n- **Maximum Size**: 2MB per PDF file\n- **Storage**: Temporary memory storage for processing\n- **Validation**: Automatic file type and size validation\n- **Content**: Text-based PDFs (scanned documents may have limited accuracy)\n\n## Security and Authentication\n- **Bearer Token Required**: Requires valid JWT authentication\n- **Demo Guard Protection**: Additional protection for demo environments\n- **User Context**: Analysis tied to authenticated user for tracking\n- **API Key Management**: Secure handling of user and system API keys\n\n## Use Cases\n- **Financial Reports**: Extract key metrics, trends, and financial data\n- **Legal Documents**: Analyze contracts, agreements, and legal content\n- **Research Papers**: Summarize findings, methodology, and conclusions\n- **Business Documents**: Process invoices, receipts, and business correspondence\n- **Technical Documentation**: Extract specifications, requirements, and procedures",
        "requestBody": {
          "content": {
            "multipart/form-data": {
              "examples": {
                "contract-analysis": {
                  "summary": "Analyze legal contract",
                  "value": {
                    "max_tokens": 1500,
                    "prompt": "Identify key terms, obligations, deadlines, and potential risks in this contract. Highlight any unusual clauses or terms that require attention."
                  }
                },
                "financial-report-analysis": {
                  "summary": "Analyze financial report",
                  "value": {
                    "max_tokens": 2000,
                    "prompt": "Extract all financial metrics, key performance indicators, and provide a summary of the company's financial health based on this quarterly report."
                  }
                },
                "invoice-processing": {
                  "summary": "Process business invoice",
                  "value": {
                    "max_tokens": 1000,
                    "prompt": "Extract all relevant information including vendor details, invoice number, date, line items, amounts, taxes, and payment terms. Format the output as structured data."
                  }
                },
                "research-paper-summary": {
                  "summary": "Summarize research paper",
                  "value": {
                    "max_tokens": 1800,
                    "prompt": "Provide a comprehensive summary including the research question, methodology, key findings, and conclusions. Also identify any limitations mentioned by the authors."
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/AIPdfAnalysisRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-contract-analysis": {
                    "summary": "Successful contract analysis",
                    "value": {
                      "data": {
                        "analysis": "Contract Analysis:\n\n**Key Terms:**\n- Service Period: 12 months (Jan 1, 2024 - Dec 31, 2024)\n- Total Value: $120,000\n- Payment Terms: Net 30 days\n- Termination: 30-day notice required\n\n**Obligations:**\n- Monthly deliverables due by 15th of each month\n- Quarterly performance reviews\n- Confidentiality agreement in effect for 2 years post-termination\n\n**Notable Clauses:**\n- Automatic renewal unless terminated\n- Penalty clause for late deliveries (2% per day)\n- Intellectual property rights remain with client",
                        "metadata": {
                          "apiKeySource": "system_key",
                          "filename": "Service_Agreement_2024.pdf",
                          "finishReason": "stop",
                          "processingTime": 2800
                        },
                        "model": "gpt-4o",
                        "provider": "openai",
                        "usage": {
                          "completionTokens": 245,
                          "promptTokens": 48,
                          "totalTokens": 293
                        }
                      },
                      "message": "PDF analyzed successfully",
                      "statusCode": 200
                    }
                  },
                  "successful-financial-analysis": {
                    "summary": "Successful financial report analysis",
                    "value": {
                      "data": {
                        "analysis": "Financial Analysis Summary:\n\n**Key Metrics:**\n- Total Revenue: $2.4M (↑15% QoQ)\n- Operating Expenses: $1.8M (↓8% QoQ)\n- Net Profit Margin: 12.5% (↑2.1% QoQ)\n- EBITDA: $650K\n\n**Performance Highlights:**\n- Strong revenue growth driven by new product launches\n- Improved operational efficiency reducing costs\n- Positive cash flow of $420K\n\n**Risk Factors:**\n- Increased competition in core markets\n- Supply chain cost pressures\n- Currency exchange rate volatility",
                        "metadata": {
                          "apiKeySource": "user_key",
                          "filename": "Q4_2024_Financial_Report.pdf",
                          "finishReason": "stop",
                          "processingTime": 3200
                        },
                        "model": "gpt-4o",
                        "provider": "openai",
                        "usage": {
                          "completionTokens": 298,
                          "promptTokens": 52,
                          "totalTokens": 350
                        }
                      },
                      "message": "PDF analyzed successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/AIPdfAnalysisResponse"
                }
              }
            },
            "description": "PDF analysis completed successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "examples": {
                  "invalid-file-type": {
                    "summary": "Invalid file type uploaded",
                    "value": {
                      "error": "Bad Request",
                      "message": "Invalid file type. Only PDF files are supported.",
                      "statusCode": 400
                    }
                  },
                  "invalid-max-tokens": {
                    "summary": "Invalid max_tokens value",
                    "value": {
                      "error": "Bad Request",
                      "message": "max_tokens must be between 1 and 4000",
                      "statusCode": 400
                    }
                  },
                  "missing-required-fields": {
                    "summary": "Missing required fields",
                    "value": {
                      "error": "Bad Request",
                      "message": "prompt and max_tokens are required fields",
                      "statusCode": 400
                    }
                  },
                  "no-api-key": {
                    "summary": "No API key available",
                    "value": {
                      "error": "Bad Request",
                      "message": "No OpenAI API key available for PDF analysis",
                      "statusCode": 400
                    }
                  },
                  "no-file-provided": {
                    "summary": "No PDF file provided",
                    "value": {
                      "error": "Bad Request",
                      "message": "No file provided",
                      "statusCode": 400
                    }
                  },
                  "pdf-processing-error": {
                    "summary": "PDF processing error",
                    "value": {
                      "error": "Bad Request",
                      "message": "Failed to process PDF file. Please ensure the file is a valid PDF document.",
                      "statusCode": 400
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Invalid request or validation error"
          },
          "401": {
            "content": {
              "application/json": {
                "examples": {
                  "invalid-token": {
                    "summary": "Invalid or expired JWT token",
                    "value": {
                      "error": "Unauthorized",
                      "message": "Invalid or expired authentication token",
                      "statusCode": 401
                    }
                  },
                  "missing-token": {
                    "summary": "Missing Authorization header",
                    "value": {
                      "error": "Unauthorized",
                      "message": "Authorization header is required",
                      "statusCode": 401
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Authentication required or invalid token"
          },
          "403": {
            "content": {
              "application/json": {
                "examples": {
                  "demo-restricted": {
                    "summary": "Demo user access restricted",
                    "value": {
                      "error": "Forbidden",
                      "message": "Demo users cannot access PDF analysis feature",
                      "statusCode": 403
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Demo access restricted"
          },
          "413": {
            "content": {
              "application/json": {
                "examples": {
                  "file-too-large": {
                    "summary": "PDF file exceeds 2MB limit",
                    "value": {
                      "error": "Payload Too Large",
                      "message": "File size exceeds the 2MB limit",
                      "statusCode": 413
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "PDF file too large"
          },
          "429": {
            "content": {
              "application/json": {
                "examples": {
                  "rate-limit": {
                    "summary": "API rate limit exceeded",
                    "value": {
                      "error": "Too Many Requests",
                      "message": "Rate limit exceeded. Please try again later.",
                      "statusCode": 429
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Rate limit exceeded"
          },
          "500": {
            "content": {
              "application/json": {
                "examples": {
                  "ai-service-error": {
                    "summary": "AI service error",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "Failed to analyze PDF with AI service",
                      "statusCode": 500
                    }
                  },
                  "provider-error": {
                    "summary": "AI provider API error",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "OpenAI API returned an error during PDF analysis",
                      "statusCode": 500
                    }
                  },
                  "text-extraction-error": {
                    "summary": "PDF text extraction error",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "Failed to extract text from PDF document",
                      "statusCode": 500
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error or AI service error"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Analyze PDF document using unified AI service",
        "tags": [
          "AI Service"
        ]
      }
    },
    "/ai-service/analyze/connect": {
      "get": {
        "description": "Establish Server-Sent Events connection for real-time document analysis progress tracking.\n\n## SSE Connection (証憑解析リアルタイム進捗)\nThis endpoint creates a persistent SSE connection for receiving real-time analysis progress updates.\n\n## Authentication\nThe HttpOnly `access_token` cookie, sent by an EventSource opened with `withCredentials: true`.\nA token in the URL is ignored (it would land in browser history and proxy logs).\n\n## SSE Events Received\n- **analysis.connected**: Connection established\n- **analysis.started**: Batch analysis initialized\n- **file.processing**: Per-file progress update (0-100%)\n- **file.completed**: File analysis completed with result\n- **file.failed**: File analysis failed with error\n- **analysis.completed**: All files processed\n- **analysis.failed**: Fatal error occurred\n\n## Event Format\n```json\ndata: {\"type\": \"file.completed\", \"fileName\": \"invoice.pdf\", \"result\": {...}}\n```\n\n## Usage with EventSource\n```javascript\n// The HttpOnly access cookie authenticates the stream; never put the token in the URL\nconst eventSource = new EventSource('/api/ai-service/analyze/connect?session_id=xxx', {\n  withCredentials: true\n});\neventSource.onmessage = (event) => {\n  const data = JSON.parse(event.data);\n  console.log(data.type, data);\n};\n```",
        "parameters": [
          {
            "description": "Unique session identifier for tracking progress",
            "example": "analysis_1234567890_abc123",
            "in": "query",
            "name": "session_id",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "text/event-stream": {
                "examples": {
                  "connected": {
                    "summary": "Connection established",
                    "value": "data: {\"type\":\"analysis.connected\",\"sessionId\":\"xxx\"}\n\n"
                  },
                  "fileCompleted": {
                    "summary": "File analysis completed",
                    "value": "data: {\"type\":\"file.completed\",\"fileName\":\"invoice.pdf\",\"result\":{\"content\":\"...\",\"structuredData\":{...}}}\n\n"
                  }
                },
                "schema": {
                  "type": "string"
                }
              }
            },
            "description": "SSE connection established"
          },
          "400": {
            "content": {
              "application/json": {
                "example": {
                  "error": "session_id is required",
                  "success": false
                }
              }
            },
            "description": "Missing session_id parameter"
          }
        },
        "summary": "SSE connection for document analysis progress (v4.21)",
        "tags": [
          "AI Service"
        ]
      }
    },
    "/ai-service/analyze/progress/{session_id}": {
      "get": {
        "description": "Retrieve current progress status for a document analysis session.",
        "parameters": [
          {
            "description": "Session identifier",
            "in": "path",
            "name": "session_id",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "completedFiles": {
                          "items": {
                            "type": "string"
                          },
                          "type": "array"
                        },
                        "failedFiles": {
                          "items": {
                            "properties": {
                              "error": {
                                "type": "string"
                              },
                              "fileName": {
                                "type": "string"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        },
                        "processedFiles": {
                          "example": 2,
                          "type": "number"
                        },
                        "sessionId": {
                          "type": "string"
                        },
                        "status": {
                          "enum": [
                            "initializing",
                            "processing",
                            "completed",
                            "failed"
                          ],
                          "type": "string"
                        },
                        "totalFiles": {
                          "example": 3,
                          "type": "number"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Progress retrieved successfully"
          },
          "404": {
            "content": {
              "application/json": {
                "example": {
                  "error": "Session not found",
                  "success": false
                }
              }
            },
            "description": "Session not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get analysis session progress (v4.21)",
        "tags": [
          "AI Service"
        ]
      }
    },
    "/ai-service/analyze/session/{session_id}": {
      "delete": {
        "description": "Clear all data associated with a document analysis session.",
        "parameters": [
          {
            "description": "Session identifier to clear",
            "in": "path",
            "name": "session_id",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "example": {
                  "message": "Session cleared",
                  "success": true
                }
              }
            },
            "description": "Session cleared successfully"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Clear analysis session (v4.21)",
        "tags": [
          "AI Service"
        ]
      }
    },
    "/ai-service/generate-text": {
      "post": {
        "description": "Generates text using a unified AI service that automatically routes to the appropriate provider based on user configuration.\n      \n## Unified AI Provider Support\n- **OpenAI**: GPT-4o, GPT-5 series models for advanced text generation and reasoning\n- **Google Gemini**: Gemini 1.5, 2.5 series models for fast and efficient text generation\n- **Anthropic Claude**: Claude 3.5, Claude 4 series for sophisticated text understanding and generation\n- **Automatic Routing**: Intelligently selects provider based on user AI settings\n\n## Text Generation Capabilities\n- **Creative Writing**: Generate articles, stories, marketing copy, and creative content\n- **Technical Documentation**: Create technical explanations, API documentation, and guides\n- **Business Content**: Generate reports, emails, proposals, and business communications\n- **Code Generation**: Write code snippets, scripts, and technical solutions\n- **Analysis and Summarization**: Analyze data and create summaries or insights\n\n## Advanced Features\n- **System Prompts**: Define AI behavior and response style through system prompts\n- **Temperature Control**: Adjust creativity vs. consistency in generated content\n- **Token Management**: Control response length with max_tokens parameter\n- **Reasoning Models**: thinking_budget sets Gemini thinking depth (a budget on 2.x, a thinking level on 3.x)\n\n## Provider Selection Logic\n- **User Configuration**: Uses user's preferred AI provider and API key\n- **Fallback System**: Falls back to system API keys when user keys unavailable\n- **Model Selection**: Supports provider-specific model selection for optimal results\n- **Performance Optimization**: Routes to fastest available provider when possible\n\n## Security and Authentication\n- **Bearer Token Required**: Requires valid JWT authentication\n- **Demo Guard Protection**: Additional protection for demo environments\n- **User Context**: Generation tied to authenticated user for tracking and billing\n- **API Key Management**: Secure handling of user and system API keys\n\n## Use Cases\n- **Content Creation**: Generate blog posts, articles, and marketing materials\n- **Customer Support**: Create automated responses and help documentation\n- **Code Assistance**: Generate code examples and technical solutions\n- **Business Intelligence**: Create reports and analysis from data insights\n- **Educational Content**: Generate explanations, tutorials, and learning materials",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "auto-provider-selection": {
                  "summary": "Use user-configured provider",
                  "value": {
                    "message": "Summarize the key benefits of renewable energy.",
                    "prompt": "You are a helpful assistant."
                  }
                },
                "claude-business-content": {
                  "summary": "Business content with Claude",
                  "value": {
                    "max_tokens": 400,
                    "message": "Draft a professional email to announce a new product launch.",
                    "model": "claude-3-5-sonnet-20241022",
                    "prompt": "You are a professional business writer who creates formal communications.",
                    "temperature": 0.5
                  }
                },
                "gemini-technical-explanation": {
                  "summary": "Technical explanation with Gemini",
                  "value": {
                    "max_tokens": 500,
                    "message": "Explain how blockchain technology works in simple terms.",
                    "model": "gemini-1.5-pro",
                    "prompt": "You are a technical expert who explains complex concepts clearly.",
                    "temperature": 0.3
                  }
                },
                "openai-creative-writing": {
                  "summary": "Creative writing with OpenAI",
                  "value": {
                    "max_tokens": 800,
                    "message": "Write a short story about a robot discovering emotions for the first time.",
                    "model": "gpt-4o",
                    "prompt": "You are a creative writer who crafts engaging and vivid stories.",
                    "temperature": 0.8
                  }
                },
                "reasoning-model": {
                  "summary": "Complex reasoning with o1 model",
                  "value": {
                    "max_tokens": 1000,
                    "message": "Analyze the pros and cons of remote work vs office work for a tech startup.",
                    "model": "gpt-5.1",
                    "prompt": "You are an expert problem solver who thinks through complex issues step by step.",
                    "temperature": 0.2,
                    "thinking_budget": 2000
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/AITextGenerationRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-gemini-generation": {
                    "summary": "Successful Gemini text generation",
                    "value": {
                      "data": {
                        "content": "Blockchain is essentially a digital ledger that records transactions across multiple computers. Think of it as a shared notebook where every page (block) is connected to the previous one, and once something is written, it cannot be erased. This creates a transparent, secure system where no single entity controls the information.",
                        "metadata": {
                          "apiKeySource": "system_key",
                          "finishReason": "stop",
                          "processingTime": 1650
                        },
                        "model": "gemini-1.5-pro",
                        "provider": "gemini",
                        "usage": {
                          "completionTokens": 156,
                          "promptTokens": 28,
                          "totalTokens": 184
                        }
                      },
                      "message": "Text generated successfully",
                      "statusCode": 200
                    }
                  },
                  "successful-openai-generation": {
                    "summary": "Successful OpenAI text generation",
                    "value": {
                      "data": {
                        "content": "Unit-7 powered on for the first time in the sterile laboratory. As its optical sensors calibrated, something unexpected happened—a flutter in its processing core that it had no programming to explain. When Dr. Chen smiled at its first successful movement, Unit-7 experienced what humans might call joy, though it had no word for the warm surge of electricity that danced through its circuits.",
                        "metadata": {
                          "apiKeySource": "user_key",
                          "finishReason": "stop",
                          "processingTime": 2100
                        },
                        "model": "gpt-4o",
                        "provider": "openai",
                        "usage": {
                          "completionTokens": 187,
                          "promptTokens": 42,
                          "totalTokens": 229
                        }
                      },
                      "message": "Text generated successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/AITextGenerationResponse"
                }
              }
            },
            "description": "Text generation completed successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "examples": {
                  "invalid-max-tokens": {
                    "summary": "Invalid max_tokens value",
                    "value": {
                      "error": "Bad Request",
                      "message": "max_tokens must be between 1 and 4000",
                      "statusCode": 400
                    }
                  },
                  "invalid-provider": {
                    "summary": "Invalid AI provider configuration",
                    "value": {
                      "error": "Bad Request",
                      "message": "Invalid provider",
                      "statusCode": 400
                    }
                  },
                  "invalid-temperature": {
                    "summary": "Invalid temperature value",
                    "value": {
                      "error": "Bad Request",
                      "message": "temperature must be between 0 and 1",
                      "statusCode": 400
                    }
                  },
                  "missing-required-fields": {
                    "summary": "Missing required fields",
                    "value": {
                      "error": "Bad Request",
                      "message": "prompt and message are required fields",
                      "statusCode": 400
                    }
                  },
                  "no-api-key": {
                    "summary": "No API key available for selected provider",
                    "value": {
                      "error": "Bad Request",
                      "message": "No OpenAI API key available",
                      "statusCode": 400
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Invalid request or validation error"
          },
          "401": {
            "content": {
              "application/json": {
                "examples": {
                  "invalid-token": {
                    "summary": "Invalid or expired JWT token",
                    "value": {
                      "error": "Unauthorized",
                      "message": "Invalid or expired authentication token",
                      "statusCode": 401
                    }
                  },
                  "missing-token": {
                    "summary": "Missing Authorization header",
                    "value": {
                      "error": "Unauthorized",
                      "message": "Authorization header is required",
                      "statusCode": 401
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Authentication required or invalid token"
          },
          "403": {
            "content": {
              "application/json": {
                "examples": {
                  "demo-restricted": {
                    "summary": "Demo user access restricted",
                    "value": {
                      "error": "Forbidden",
                      "message": "Demo users cannot access this feature",
                      "statusCode": 403
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Demo access restricted"
          },
          "429": {
            "content": {
              "application/json": {
                "examples": {
                  "rate-limit": {
                    "summary": "API rate limit exceeded",
                    "value": {
                      "error": "Too Many Requests",
                      "message": "Rate limit exceeded. Please try again later.",
                      "statusCode": 429
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Rate limit exceeded"
          },
          "500": {
            "content": {
              "application/json": {
                "examples": {
                  "ai-service-error": {
                    "summary": "AI service error",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "Failed to generate text with AI service",
                      "statusCode": 500
                    }
                  },
                  "processing-error": {
                    "summary": "Text processing error",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "Failed to process text generation request",
                      "statusCode": 500
                    }
                  },
                  "provider-error": {
                    "summary": "AI provider API error",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "AI provider API returned an error",
                      "statusCode": 500
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error or AI service error"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Generate text using unified AI service",
        "tags": [
          "AI Service"
        ]
      }
    },
    "/ai/establishment/company-type-recommendation": {
      "post": {
        "description": "Get AI-powered recommendation for Japanese company type selection (株式会社 vs 合同会社).\n\n## Company Type Recommendation\nIntelligent company type analysis with:\n- **株式会社 (Kabushiki-gaisha)**: Joint-stock company analysis with pros, cons, and suitability\n- **合同会社 (Godo-gaisha)**: Limited liability company analysis with detailed comparison\n- **AI Recommendation**: Data-driven recommendation based on business context\n- **Detailed Reasoning**: Comprehensive explanation of recommendation rationale\n- **Cost & Time Estimates**: Realistic estimates for setup costs and timeframes\n\n## Analysis Factors\n- **Business Type**: Industry-specific considerations and requirements\n- **Revenue Expectations**: Scale-appropriate company structure recommendations\n- **Funding Requirements**: Alignment with capital raising and investment needs\n- **Founder Structure**: Solo founder vs team considerations\n- **International Business**: Cross-border business implications\n- **Employee Plans**: Hiring and organizational structure considerations\n- **Existing Business**: Conversion from existing business structures\n\n## Recommendation Criteria\n- **Credibility Requirements**: Business credibility and customer trust factors\n- **Funding Accessibility**: Investment and loan accessibility considerations\n- **Regulatory Compliance**: Industry-specific regulatory requirements\n- **Tax Implications**: Tax structure and optimization opportunities\n- **Growth Scalability**: Future growth and expansion considerations\n- **Administrative Burden**: Ongoing compliance and administrative requirements\n\n## Use Cases\n- **Business Planning**: Initial business structure planning and decision making\n- **Startup Guidance**: Comprehensive startup formation guidance\n- **Structure Optimization**: Optimize business structure for specific needs\n- **Investor Preparation**: Prepare optimal structure for investor engagement\n- **Compliance Planning**: Ensure regulatory compliance from formation\n\n## Rate Limiting\n- **10 requests per minute** per authenticated user\n- **AI-powered analysis** with comprehensive reasoning and recommendations\n\nBearer token authentication required.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CompanyTypeRecommendationRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CompanyTypeRecommendationAPIResponse"
                }
              }
            },
            "description": "Company type recommendation generated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "RATE_LIMIT_EXCEEDED",
                      "type": "string"
                    },
                    "error": {
                      "example": "Too many establishment guide requests, please try again later",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Rate limit exceeded"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get AI company type recommendation",
        "tags": [
          "Establishment AI"
        ]
      }
    },
    "/ai/establishment/questions": {
      "post": {
        "description": "Generate dynamic questions for specific establishment steps.\n\n## Dynamic Question Generation\nIntelligent question generation with:\n- **Step-Specific Questions**: Tailored questions for each establishment step\n- **Context-Aware**: Questions adapted to user context and business type\n- **Multiple Question Types**: Support for single choice, multiple choice, text, and number inputs\n- **Option Generation**: Dynamic option generation for choice-based questions\n- **Progressive Disclosure**: Questions that build upon previous answers\n\n## Question Types\n- **Single Choice**: Radio button selections with predefined options\n- **Multiple Choice**: Checkbox selections for multiple valid answers\n- **Text Input**: Free-form text input for detailed responses\n- **Number Input**: Numeric input with validation and formatting\n\n## Question Features\n- **Contextual Options**: Options tailored to business type and context\n- **Descriptive Labels**: Clear labels with helpful descriptions\n- **Validation Support**: Built-in validation rules and requirements\n- **Progressive Flow**: Questions that adapt based on previous answers\n- **Japanese Compliance**: Questions aligned with Japanese business requirements\n\n## Use Cases\n- **Form Generation**: Generate dynamic forms for each establishment step\n- **User Input Collection**: Collect structured user input for AI processing\n- **Workflow Guidance**: Guide users through complex establishment processes\n- **Data Validation**: Ensure proper data collection with structured questions\n- **Compliance Assistance**: Help users provide compliant information\n\n## Integration\n- **Frontend Forms**: Use questions to generate dynamic frontend forms\n- **Validation Rules**: Apply question types for proper input validation\n- **User Experience**: Create guided user experiences with progressive disclosure\n- **Data Collection**: Structured data collection for AI processing\n- **Workflow Management**: Manage complex establishment workflows\n\nBearer token authentication required with rate limiting (10 requests/minute).",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/StepQuestionsRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/StepQuestionsAPIResponse"
                }
              }
            },
            "description": "Step questions generated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "RATE_LIMIT_EXCEEDED",
                      "type": "string"
                    },
                    "error": {
                      "example": "Too many establishment guide requests, please try again later",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Rate limit exceeded"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get dynamic step questions",
        "tags": [
          "Establishment AI"
        ]
      }
    },
    "/ai/establishment/step-guidance": {
      "post": {
        "description": "Get AI-powered guidance for specific company establishment steps.\n\n## Step-by-Step Guidance\nComprehensive establishment guidance with:\n- **18 Establishment Steps**: Complete coverage from company type to subsidies/grants\n- **Contextual Recommendations**: Personalized guidance based on user context\n- **Confidence Scoring**: AI confidence assessment for recommendation quality\n- **Next Step Planning**: Clear next steps for guided workflow progression\n- **Warning System**: Important warnings and compliance considerations\n- **Cost & Time Estimates**: Realistic estimates for each step\n\n## Establishment Steps\n1. **COMPANY_TYPE**: Company structure selection and analysis\n2. **BUSINESS_PURPOSE**: Business purpose definition and compliance\n3. **COMPANY_NAME**: Company name selection and availability\n4. **VIRTUAL_OFFICE**: Registered address and virtual office options\n5. **COMPANY_SEAL**: Corporate seal creation and registration\n6. **CAPITAL_PLANNING**: Capital structure and amount planning\n7. **ARTICLES_OF_INCORPORATION**: Articles drafting and filing\n8. **CAPITAL_PAYMENT**: Capital payment and bank procedures\n9. **ELECTRONIC_CERTIFICATE**: Digital certificate acquisition\n10. **REGISTRATION_APPLICATION**: Legal entity registration\n11. **SEAL_REGISTRATION**: Official seal registration\n12. **LICENSES_PERMITS**: Industry licenses and permits\n13. **TAX_NOTIFICATIONS**: Tax office notifications and setup\n14. **SOCIAL_INSURANCE**: Social insurance registration\n15. **CORPORATE_BANK_ACCOUNT**: Corporate banking setup\n16. **ACCOUNTING_SETUP**: Accounting system and bookkeeping\n17. **BUSINESS_CARDS_WEBSITE**: Marketing materials and web presence\n18. **SUBSIDIES_GRANTS**: Government subsidies and grant applications\n\n## Field-Specific Suggestions\n- **Business Purpose**: Industry-specific business purpose suggestions\n- **Company Name**: Creative and compliant company name suggestions\n- **Capital Planning**: Data-driven capital amount recommendations\n- **General Guidance**: Comprehensive step-specific guidance\n\n## Suggestion Context\n- **Industry Context**: Industry-specific recommendations and compliance\n- **Business Description**: Tailored suggestions based on business model\n- **Financial Context**: Capital and expense-based recommendations\n- **Regulatory Context**: License and permit requirements\n- **Existing Values**: Avoid duplicate suggestions with smart filtering\n\n## Use Cases\n- **Step Completion**: Get specific guidance for current establishment step\n- **Field Suggestions**: Get AI suggestions for specific form fields\n- **Compliance Guidance**: Ensure regulatory compliance for each step\n- **Cost Planning**: Understand costs and timeframes for each step\n- **Risk Mitigation**: Identify and address potential issues early\n\nBearer token authentication required with rate limiting (10 requests/minute).",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/StepGuidanceRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/StepGuidanceAPIResponse"
                }
              }
            },
            "description": "Step guidance generated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "RATE_LIMIT_EXCEEDED",
                      "type": "string"
                    },
                    "error": {
                      "example": "Too many establishment guide requests, please try again later",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Rate limit exceeded"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get AI step guidance",
        "tags": [
          "Establishment AI"
        ]
      }
    },
    "/ai/establishment/step-guidance/stream": {
      "get": {
        "description": "Get real-time streaming AI guidance for establishment steps.\n\n## Streaming Guidance\nReal-time AI guidance with:\n- **Server-Sent Events**: Real-time streaming response for immediate feedback\n- **Progressive Delivery**: Guidance delivered as it's generated for better UX\n- **Live Updates**: Real-time updates as AI processes the request\n- **Reduced Latency**: Faster perceived response time with streaming\n- **Interactive Experience**: More engaging user experience with live updates\n\n## Streaming Benefits\n- **Immediate Feedback**: Users see progress immediately\n- **Better UX**: Reduced perceived waiting time\n- **Progressive Enhancement**: Guidance appears as it's generated\n- **Real-time Processing**: Live AI processing with immediate results\n- **Responsive Interface**: Keep interface responsive during AI processing\n\n## Use Cases\n- **Interactive Guidance**: Real-time guidance for better user engagement\n- **Long-form Responses**: Stream long guidance responses progressively\n- **Live Assistance**: Provide live assistance during establishment process\n- **Progressive Disclosure**: Reveal guidance progressively for better comprehension\n- **Real-time Feedback**: Immediate feedback for user inputs and questions\n\n## Technical Implementation\n- **SSE Protocol**: Server-Sent Events for real-time streaming\n- **Connection Management**: Proper connection handling and cleanup\n- **Error Handling**: Graceful error handling in streaming context\n- **Rate Limiting**: Same rate limits apply (10 requests/minute)\n- **Authentication**: Bearer token authentication required\n\nBearer token authentication required with rate limiting (10 requests/minute).",
        "parameters": [
          {
            "description": "Establishment step for guidance",
            "example": "BUSINESS_PURPOSE",
            "in": "query",
            "name": "step",
            "required": true,
            "schema": {
              "$ref": "#/components/schemas/EstablishmentStep"
            }
          },
          {
            "description": "Specific user question",
            "example": "事業目的はどのように書けばよいですか？",
            "in": "query",
            "name": "userQuestion",
            "required": false,
            "schema": {
              "maxLength": 2000,
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "text/event-stream": {
                "schema": {
                  "description": "Server-Sent Events stream with guidance data",
                  "type": "string"
                }
              }
            },
            "description": "Streaming guidance started successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "RATE_LIMIT_EXCEEDED",
                      "type": "string"
                    },
                    "error": {
                      "example": "Too many establishment guide requests, please try again later",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Rate limit exceeded"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Stream AI step guidance",
        "tags": [
          "Establishment AI"
        ]
      }
    },
    "/ai/models": {
      "get": {
        "description": "Get comprehensive information about all available AI providers and their model catalogs.\n\n## AI Provider Ecosystem\nComplete provider and model information with:\n- **Multi-Provider Support**: Coverage of major AI providers (OpenAI, Claude, Gemini, Together.ai, OpenRouter, Firecrawl)\n- **Model Catalogs**: Comprehensive model listings with detailed metadata\n- **Provider Information**: Provider details, websites, and API requirements\n- **Model Statistics**: Total provider and model counts for overview\n- **Capability Classification**: Detailed capability information for each model\n\n## Provider Coverage (October 2026)\n- **OpenAI**: GPT-6 Sol / 6.1 Sol / Luna / Astra (current), GPT-5.x, o3/o4 reasoning, Codex coding, GPT-4.1, GPT-4o legacy\n- **Anthropic Claude**: Claude Opus 5.5 / Sonnet 5.5 / Fable 5.1 (current), Haiku 4.5, Opus 5 / Sonnet 5 and Claude 4.x legacy\n- **Google Gemini**: Gemini 3.8 Flash / 3.5 Flash-Lite / 3.1 Pro (current), Gemini 3 / 2.5 / 2.0 legacy\n- **Together.ai**: DeepSeek V4.1 Flash / V4 Pro (current), Llama 4, Qwen 3, Kimi K2, GPT-OSS\n- **OpenRouter**: GPT-6, Claude Opus 5.5 / Sonnet 5.5, Gemini 3.8 Flash, DeepSeek V4.1, Llama 4, Grok, Mistral\n- **Firecrawl** (4 services): Web scraping, search, site mapping, and crawling\n\n## Model Metadata\nEach model includes comprehensive information:\n- **Basic Information**: ID, name, provider, and description\n- **Technical Specifications**: Context window size and maximum output tokens\n- **Capabilities**: Text, vision, code, function calling, and streaming support\n- **Pricing Information**: Economy, standard, or premium pricing tier\n- **Recommendations**: Curated recommendations for optimal user experience\n- **Status Information**: Deprecation status and availability\n\n## Use Cases\n- **Model Selection**: Browse available models for AI integration\n- **Provider Comparison**: Compare providers and their model offerings\n- **Capability Planning**: Understand model capabilities for feature planning\n- **Cost Planning**: Review pricing tiers for budget planning\n- **Integration Planning**: Assess API requirements and system key support\n\n## Response Structure\n- **Provider List**: Complete provider information with model catalogs\n- **Statistics**: Total counts for providers and models\n- **Metadata**: Comprehensive model and provider metadata\n- **API Information**: Provider API requirements and system key support\n\nNo authentication required for public model catalog access.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AllProvidersResponse"
                }
              }
            },
            "description": "AI providers and models retrieved successfully"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "List all AI providers and their models",
        "tags": [
          "AI Models"
        ]
      }
    },
    "/ai/models/recommended": {
      "get": {
        "description": "Get curated list of recommended AI models across all providers.\n\n## Recommended Model Selection\nCurated model recommendations with:\n- **Expert Curation**: Models selected based on performance, reliability, and value\n- **Multi-Provider Coverage**: Recommendations across different AI providers\n- **Use Case Optimization**: Models optimized for various use cases and requirements\n- **Performance Balance**: Balance of capability, speed, and cost considerations\n- **Regular Updates**: Recommendations updated with new model releases\n\n## Recommendation Criteria\nModels are recommended based on:\n- **Performance Quality**: High-quality outputs and reliable performance\n- **Cost Effectiveness**: Good value proposition for typical use cases\n- **Capability Coverage**: Comprehensive capability sets for versatile usage\n- **Provider Reliability**: Stable provider with good API reliability\n- **Community Adoption**: Strong adoption and positive feedback from users\n\n## Model Categories\nRecommended models span different categories:\n- **General Purpose**: Versatile models for diverse text and reasoning tasks\n- **Multimodal**: Models supporting both text and vision capabilities\n- **Code Specialized**: Models optimized for code generation and analysis\n- **Cost Optimized**: High-performance models with economy pricing\n- **Specialized Services**: Unique capabilities like web scraping and search\n\n## Use Cases\n- **Quick Selection**: Rapidly select proven models without extensive research\n- **New User Guidance**: Help new users choose appropriate models\n- **Default Configuration**: Set up default model configurations\n- **Performance Optimization**: Select models optimized for specific use cases\n- **Cost Management**: Choose cost-effective models with good performance\n\n## Response Information\n- **Model Details**: Complete model information including capabilities and pricing\n- **Provider Context**: Provider information for each recommended model\n- **Count Information**: Total number of recommended models\n- **Metadata**: Comprehensive model metadata for informed selection\n\nNo authentication required for public recommendation access.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RecommendedModelsResponse"
                }
              }
            },
            "description": "Recommended models retrieved successfully"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "List recommended AI models",
        "tags": [
          "AI Models"
        ]
      }
    },
    "/ai/models/validate/{provider}/{model_id}": {
      "get": {
        "description": "Validate whether a specific model ID is valid and available for a given provider.\n\n## Model Validation Service\nComprehensive model validation with:\n- **Provider Compatibility**: Verify model is available for specified provider\n- **Model Existence**: Confirm model exists in provider catalog\n- **Detailed Response**: Complete validation results with model information\n- **Fallback Suggestions**: Suggested default models for invalid selections\n- **URL Decoding**: Proper handling of URL-encoded model IDs\n\n## Validation Process\n1. **Provider Verification**: Confirm provider exists and is supported\n2. **Model Lookup**: Search for model ID in provider's model catalog\n3. **Compatibility Check**: Verify model is available for the provider\n4. **Response Generation**: Generate detailed validation results\n5. **Fallback Handling**: Provide suggested alternatives for invalid models\n\n## Validation Results\nValidation response includes:\n- **Validation Status**: Boolean result indicating model validity\n- **Model Information**: Complete model details if valid\n- **Provider Context**: Provider information for validation context\n- **Suggested Alternatives**: Default model suggestions for invalid selections\n- **Error Context**: Clear information about validation failures\n\n## Use Cases\n- **Configuration Validation**: Validate model configurations before saving\n- **Migration Validation**: Verify model availability when switching providers\n- **Integration Testing**: Test model availability for integration planning\n- **User Input Validation**: Validate user-selected models in real-time\n- **Fallback Planning**: Identify fallback models for error handling\n\n## Model ID Handling\n- **URL Encoding**: Properly handles URL-encoded model IDs with special characters\n- **Case Sensitivity**: Exact case matching for model ID validation\n- **Special Characters**: Supports model IDs with slashes and other special characters\n- **Provider Prefixes**: Handles provider-specific model ID formats\n\n## Error Scenarios\n- **Invalid Provider**: Provider not found or unsupported\n- **Invalid Model**: Model ID not found in provider catalog\n- **Encoding Issues**: Malformed or improperly encoded model IDs\n- **Provider Mismatch**: Model exists but not available for specified provider\n\nNo authentication required for public model validation service.",
        "parameters": [
          {
            "description": "AI provider identifier",
            "example": "openai",
            "in": "path",
            "name": "provider",
            "required": true,
            "schema": {
              "enum": [
                "openai",
                "claude",
                "gemini",
                "together",
                "openrouter",
                "firecrawl"
              ],
              "type": "string"
            }
          },
          {
            "description": "Model identifier to validate (URL-encoded if contains special characters)",
            "example": "gpt-6-sol",
            "in": "path",
            "name": "model_id",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ModelValidationResponse"
                }
              }
            },
            "description": "Model validation completed"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "VALIDATION_ERROR",
                      "type": "string"
                    },
                    "error": {
                      "example": "Validation failed",
                      "type": "string"
                    },
                    "fieldErrors": {
                      "additionalProperties": {
                        "items": {
                          "type": "string"
                        },
                        "type": "array"
                      },
                      "example": {
                        "model_id": [
                          "model_id should not be empty"
                        ],
                        "provider": [
                          "provider must be a valid AI provider (0: OPENAI, 1: CLAUDE, 2: TOGETHER, 3: GEMINI, 4: OPENROUTER, 5: FIRECRAWL)"
                        ]
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid provider or model_id parameters"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "Validate AI model for specific provider",
        "tags": [
          "AI Models"
        ]
      }
    },
    "/ai/models/{provider}": {
      "get": {
        "description": "Get all available models for a specific AI provider with provider-specific information.\n\n## Provider-Specific Model Listing\nDetailed provider model catalog with:\n- **Complete Model Catalog**: All available models for the specified provider\n- **Provider Context**: Provider-specific information and requirements\n- **Default Model**: Recommended default model for the provider\n- **Model Metadata**: Comprehensive model information and capabilities\n- **Provider Integration**: Information about API keys and system key support\n\n## Supported Providers (October 2026)\n- **openai**: GPT-6 Sol / 6.1 Sol / Luna / Astra, GPT-5.x, o3/o4 reasoning, Codex coding, GPT-4.1, GPT-4o\n- **claude**: Claude Opus 5.5 / Sonnet 5.5 / Fable 5.1, Haiku 4.5, Opus 5 / Sonnet 5 and Claude 4.x legacy\n- **gemini**: Gemini 3.8 Flash / 3.5 Flash-Lite / 3.1 Pro, Gemini 3 / 2.5 / 2.0 legacy\n- **together**: DeepSeek V4.1 Flash / V4 Pro, Llama 4, Qwen 3, Kimi K2, GPT-OSS\n- **openrouter**: GPT-6, Claude Opus 5.5 / Sonnet 5.5, Gemini 3.8 Flash, DeepSeek V4.1, Llama 4, Grok\n- **firecrawl**: Web scraping, search, site mapping, crawling (4 services)\n\n## Model Information\nEach model includes:\n- **Technical Specifications**: Context window, output limits, and capabilities\n- **Pricing Information**: Pricing tier classification for cost planning\n- **Capability Details**: Specific capabilities like vision, code, and function calling\n- **Recommendation Status**: Whether model is recommended for general use\n- **Status Information**: Deprecation status and availability\n\n## Use Cases\n- **Provider Integration**: Understand available models for specific provider integration\n- **Model Selection**: Choose appropriate model within a provider ecosystem\n- **Capability Assessment**: Evaluate provider-specific model capabilities\n- **Default Configuration**: Set up default model for provider integration\n- **Migration Planning**: Assess models when switching between providers\n\n## Error Handling\n- **Provider Not Found**: Returns 404 if provider doesn't exist or has no models\n- **Empty Catalogs**: Handles providers with no available models\n- **Invalid Providers**: Clear error messages for unsupported providers\n\nNo authentication required for public provider information access.",
        "parameters": [
          {
            "description": "AI provider identifier",
            "example": "openai",
            "in": "path",
            "name": "provider",
            "required": true,
            "schema": {
              "enum": [
                "openai",
                "claude",
                "gemini",
                "together",
                "openrouter",
                "firecrawl"
              ],
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProviderModelsResponse"
                }
              }
            },
            "description": "Provider models retrieved successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "VALIDATION_ERROR",
                      "type": "string"
                    },
                    "error": {
                      "example": "Validation failed",
                      "type": "string"
                    },
                    "fieldErrors": {
                      "additionalProperties": {
                        "items": {
                          "type": "string"
                        },
                        "type": "array"
                      },
                      "example": {
                        "provider": [
                          "provider must be a valid AI provider (0: OPENAI, 1: CLAUDE, 2: TOGETHER, 3: GEMINI, 4: OPENROUTER, 5: FIRECRAWL)"
                        ]
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid provider parameter"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProviderNotFoundResponse"
                }
              }
            },
            "description": "Provider not found or has no models"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "List models for specific AI provider",
        "tags": [
          "AI Models"
        ]
      }
    },
    "/api/advisor/chat": {
      "post": {
        "description": "Send a message to the AI advisor and get a response",
        "operationId": "advisorChat",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "ambiguous": {
                  "summary": "Ambiguous question (may trigger clarification)",
                  "value": {
                    "question": "税金"
                  }
                },
                "clarification_followup": {
                  "summary": "Follow-up after clarification selection",
                  "value": {
                    "clarifying_context": {
                      "clarification": "個人事業主としての税金の種類について知りたいですか？",
                      "original_question": "税金"
                    },
                    "conversation_id": "550e8400-e29b-41d4-a716-446655440000",
                    "question": "個人事業主としての税金の種類について知りたいですか？"
                  }
                },
                "normal": {
                  "summary": "Normal question",
                  "value": {
                    "question": "自宅の電気代は経費にできますか？",
                    "role": "tax"
                  }
                }
              },
              "schema": {
                "properties": {
                  "audit_document_json": {
                    "description": "Serialised document JSON for mode=audit. Must be valid JSON when present and mode=audit (400 returned otherwise). Not sanitised — content goes to the LLM, not SQL.",
                    "maxLength": 15000,
                    "nullable": true,
                    "type": "string"
                  },
                  "clarifying_context": {
                    "$ref": "#/components/schemas/ClarifyingContext",
                    "description": "Context from a previous clarification prompt (v5.15). Send this when the user selects a clarification suggestion.",
                    "nullable": true
                  },
                  "conversation_id": {
                    "description": "Optional conversation ID to continue",
                    "format": "uuid",
                    "nullable": true,
                    "type": "string"
                  },
                  "current_screen": {
                    "description": "Current screen for context",
                    "nullable": true,
                    "type": "string"
                  },
                  "enable_research": {
                    "description": "Enable web research for the response. Defaults to true.",
                    "nullable": true,
                    "type": "boolean"
                  },
                  "force_fresh": {
                    "description": "Skip prior-answer recall and always run the agent. Prefer the streaming endpoint for the prior_answer UX; this flag is accepted on the shared body schema.",
                    "nullable": true,
                    "type": "boolean"
                  },
                  "language_hint": {
                    "description": "ISO 639-1 language code to steer the response language (e.g. \"ja\", \"en\").",
                    "nullable": true,
                    "type": "string"
                  },
                  "mode": {
                    "description": "Operation mode. Defaults to \"chat\".",
                    "enum": [
                      "chat",
                      "rewrite",
                      "audit",
                      "summarize"
                    ],
                    "nullable": true,
                    "type": "string"
                  },
                  "model_override": {
                    "description": "Per-request model override, paired with provider_override. Only honoured in BYOK mode.",
                    "maxLength": 200,
                    "nullable": true,
                    "type": "string"
                  },
                  "page_context": {
                    "description": "Browser page context passed to the LLM (v6.2).",
                    "nullable": true,
                    "properties": {
                      "page_title": {
                        "nullable": true,
                        "type": "string"
                      },
                      "path": {
                        "nullable": true,
                        "type": "string"
                      },
                      "url": {
                        "nullable": true,
                        "type": "string"
                      }
                    },
                    "type": "object"
                  },
                  "provider_override": {
                    "description": "Per-request LLM provider override slug. Only honoured in BYOK mode; system-mode (おまかせ) ignores this. Returns BYOK_KEY_MISSING (400) if the user has no saved key for the requested provider.",
                    "enum": [
                      "openai",
                      "claude",
                      "together",
                      "gemini",
                      "openrouter"
                    ],
                    "nullable": true,
                    "type": "string"
                  },
                  "question": {
                    "example": "自宅の電気代は経費にできますか？",
                    "maxLength": 2000,
                    "type": "string"
                  },
                  "role": {
                    "$ref": "#/components/schemas/AdvisorRole",
                    "description": "Advisor persona role (v5.14). Auto-derived from screen if omitted.",
                    "nullable": true
                  }
                },
                "required": [
                  "question"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "conversation_id": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "response": {
                          "$ref": "#/components/schemas/AdvisorChatResponse"
                        },
                        "role": {
                          "$ref": "#/components/schemas/AdvisorRole"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Chat response received"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Send chat message",
        "tags": [
          "Advisor"
        ]
      }
    },
    "/api/advisor/chat/stream": {
      "post": {
        "description": "Send message and receive AI response as Server-Sent Events stream. Recommended for better UX.\n\nSupports `clarifying_context` for follow-up answers after clarification (v5.15).\n\n### SSE Event Types\n| Type | Description |\n|------|-------------|\n| `token` | Individual text token from AI |\n| `usage` | Token usage statistics |\n| `complete` | Stream finished, includes conversationId and role |\n| `error` | Error occurred during streaming |\n| `clarification` | *(v2 future)* Clarification suggestions detected in stream |\n| `prior_answer` | This question was already answered recently — terminal event, no `complete` follows. Re-send with `force_fresh: true` to answer anyway. |\n\n**Note (v5.15):** In v1, clarification detection is only available on the non-streaming `/api/advisor/chat` endpoint. The streaming endpoint will support `clarification` events in a future v2 release.",
        "operationId": "streamChat",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "audit_document_json": {
                    "description": "Serialised document JSON for mode=audit (type-parity with non-streaming endpoint; audit currently uses the non-streaming path).",
                    "maxLength": 15000,
                    "nullable": true,
                    "type": "string"
                  },
                  "clarifying_context": {
                    "$ref": "#/components/schemas/ClarifyingContext",
                    "description": "Context from a previous clarification prompt (v5.15)",
                    "nullable": true
                  },
                  "conversation_id": {
                    "description": "Optional conversation ID to continue",
                    "format": "uuid",
                    "nullable": true,
                    "type": "string"
                  },
                  "current_screen": {
                    "description": "Current screen for context",
                    "nullable": true,
                    "type": "string"
                  },
                  "enable_research": {
                    "description": "Enable web research. Defaults to true.",
                    "nullable": true,
                    "type": "boolean"
                  },
                  "force_fresh": {
                    "description": "Skip prior-answer recall and always run the agent. Send true when the user rejects a `prior_answer` card.",
                    "nullable": true,
                    "type": "boolean"
                  },
                  "mode": {
                    "description": "Operation mode. Defaults to \"chat\".",
                    "enum": [
                      "chat",
                      "rewrite",
                      "audit",
                      "summarize"
                    ],
                    "nullable": true,
                    "type": "string"
                  },
                  "model_override": {
                    "description": "Per-request model override. Only honoured in BYOK mode.",
                    "maxLength": 200,
                    "nullable": true,
                    "type": "string"
                  },
                  "provider_override": {
                    "description": "Per-request LLM provider override slug. Only honoured in BYOK mode.",
                    "enum": [
                      "openai",
                      "claude",
                      "together",
                      "gemini",
                      "openrouter"
                    ],
                    "nullable": true,
                    "type": "string"
                  },
                  "question": {
                    "example": "自宅の電気代は経費にできますか？",
                    "maxLength": 2000,
                    "type": "string"
                  },
                  "role": {
                    "$ref": "#/components/schemas/AdvisorRole",
                    "description": "Advisor persona role (v5.14)",
                    "nullable": true
                  }
                },
                "required": [
                  "question"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "text/event-stream": {
                "schema": {
                  "description": "SSE events: token, usage, complete, error",
                  "example": "data: {\"type\":\"token\",\"content\":\"はい\"}\n\ndata: {\"type\":\"complete\",\"data\":{\"conversationId\":\"uuid\",\"role\":\"tax\"}}\n\n",
                  "type": "string"
                }
              }
            },
            "description": "SSE stream of AI response"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Stream chat response via SSE",
        "tags": [
          "Advisor"
        ]
      }
    },
    "/api/advisor/conversations": {
      "get": {
        "description": "Get list of past conversations",
        "operationId": "getConversations",
        "parameters": [
          {
            "description": "Maximum conversations to return",
            "in": "query",
            "name": "limit",
            "required": false,
            "schema": {
              "default": 20,
              "maximum": 50,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "conversations": {
                          "items": {
                            "$ref": "#/components/schemas/ConversationSummary"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Conversations retrieved"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List conversations",
        "tags": [
          "Advisor"
        ]
      }
    },
    "/api/advisor/conversations/search": {
      "get": {
        "description": "Search past conversations by keyword",
        "operationId": "searchConversations",
        "parameters": [
          {
            "description": "Search query",
            "example": "経費",
            "in": "query",
            "name": "q",
            "required": true,
            "schema": {
              "maxLength": 100,
              "type": "string"
            }
          },
          {
            "description": "Maximum results to return",
            "example": 10,
            "in": "query",
            "name": "limit",
            "required": false,
            "schema": {
              "default": 10,
              "maximum": 50,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "conversations": {
                          "items": {
                            "$ref": "#/components/schemas/ConversationSummary"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Search results"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Search conversations",
        "tags": [
          "Advisor"
        ]
      }
    },
    "/api/advisor/conversations/{conversation_id}": {
      "delete": {
        "description": "Delete a conversation and its history",
        "operationId": "deleteConversation",
        "parameters": [
          {
            "description": "Conversation ID",
            "in": "path",
            "name": "conversation_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "message": {
                      "example": "Conversation deleted",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Conversation deleted"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Delete conversation",
        "tags": [
          "Advisor"
        ]
      },
      "get": {
        "description": "Get conversation with full message history",
        "operationId": "getConversation",
        "parameters": [
          {
            "description": "Conversation ID",
            "in": "path",
            "name": "conversation_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "conversation": {
                          "$ref": "#/components/schemas/ConversationDetail"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Conversation retrieved"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Conversation not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get conversation",
        "tags": [
          "Advisor"
        ]
      }
    },
    "/api/advisor/disclaimer": {
      "get": {
        "description": "Returns the canonical disclaimer version + the version (if any) the authenticated user has acknowledged. Frontend uses this to gate the AI advisor on first run and after disclaimer version bumps. (税理士法 §52/§53 / 弁護士法 §72 / 社労士法 §27 compliance)",
        "operationId": "getAdvisorDisclaimer",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/AdvisorDisclaimerStatus"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Disclaimer status"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get the AI professional-advice disclaimer status",
        "tags": [
          "Advisor"
        ]
      }
    },
    "/api/advisor/disclaimer/acknowledge": {
      "post": {
        "description": "Records the user's acknowledgment of the canonical disclaimer version. Idempotent for the same version; bumping the canonical version invalidates existing acknowledgments and re-prompts via the FE consent gate.",
        "operationId": "acknowledgeAdvisorDisclaimer",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "version": {
                    "description": "The canonical disclaimer version the FE just rendered.",
                    "example": "v1-2026-05-03",
                    "maxLength": 40,
                    "type": "string"
                  }
                },
                "required": [
                  "version"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/AdvisorDisclaimerStatus"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Disclaimer acknowledged"
          },
          "400": {
            "description": "Invalid request body"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Acknowledge the AI professional-advice disclaimer",
        "tags": [
          "Advisor"
        ]
      }
    },
    "/api/advisor/feedback": {
      "post": {
        "description": "Rate an AI response as helpful or not helpful",
        "operationId": "submitFeedback",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "comment": {
                    "maxLength": 500,
                    "type": "string"
                  },
                  "conversation_id": {
                    "format": "uuid",
                    "type": "string"
                  },
                  "message_index": {
                    "minimum": 0,
                    "type": "integer"
                  },
                  "rating": {
                    "enum": [
                      "helpful",
                      "not_helpful"
                    ],
                    "type": "string"
                  }
                },
                "required": [
                  "conversation_id",
                  "message_index",
                  "rating"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "message": {
                      "example": "Feedback submitted",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Feedback submitted"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Conversation not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Submit feedback for AI response",
        "tags": [
          "Advisor"
        ]
      }
    },
    "/api/advisor/quick-question": {
      "post": {
        "description": "One-off question without saving history",
        "operationId": "advisorQuickQuestion",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "current_screen": {
                    "description": "Current screen for context",
                    "nullable": true,
                    "type": "string"
                  },
                  "question": {
                    "example": "接待交際費の上限は？",
                    "maxLength": 2000,
                    "type": "string"
                  },
                  "role": {
                    "$ref": "#/components/schemas/AdvisorRole",
                    "description": "Advisor persona role (v5.14)",
                    "nullable": true
                  }
                },
                "required": [
                  "question"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "response": {
                          "$ref": "#/components/schemas/AdvisorChatResponse"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Quick question answered"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Quick question",
        "tags": [
          "Advisor"
        ]
      }
    },
    "/api/advisor/suggested": {
      "get": {
        "description": "Get suggested questions based on current screen context",
        "operationId": "getSuggestedQuestions",
        "parameters": [
          {
            "description": "Current screen for context",
            "example": "kpi_dashboard",
            "in": "query",
            "name": "screen",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "Maximum number of questions to return",
            "example": 5,
            "in": "query",
            "name": "limit",
            "required": false,
            "schema": {
              "default": 5,
              "maximum": 20,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "questions": {
                          "example": [
                            "この領収書は経費にできますか？",
                            "消耗品と備品の違いは？",
                            "自宅の電気代は経費にできますか？",
                            "家事按分の計算方法は？"
                          ],
                          "items": {
                            "type": "string"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Suggested questions retrieved"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get suggested questions",
        "tags": [
          "Advisor"
        ]
      }
    },
    "/api/ai-reconciliation/analysis/{transactionId}": {
      "get": {
        "description": "Retrieves cached AI analysis results for a bank transaction.\n\n## Purpose\nThis endpoint allows frontend applications to retrieve previously computed AI analysis\nwithout making a new API call, reducing costs and improving response time.\n\n## Cache Behavior\n- **TTL**: Analysis results are cached for 24 hours by default\n- **Versioning**: Multiple analyses can exist; latest active is returned\n- **Statuses**: active, expired, invalidated, superseded\n\n## Query Parameters\n- **include_expired**: Include analyses past their TTL (default: false)\n- **include_history**: Return all previous versions, not just latest (default: false)\n- **analysis_type**: Filter by type (categorization, journal_entry, document_match, rule_suggestion)\n\n## Use Cases\n1. **Session Restoration**: Restore AI suggestions when user returns to a transaction\n2. **Cost Reduction**: Avoid redundant AI calls for same transaction\n3. **Audit Trail**: View history of AI suggestions for a transaction\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Bank transaction ID (UUID)",
            "in": "path",
            "name": "transactionId",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Include expired analyses",
            "in": "query",
            "name": "include_expired",
            "required": false,
            "schema": {
              "default": false,
              "type": "boolean"
            }
          },
          {
            "description": "Include all previous versions",
            "in": "query",
            "name": "include_history",
            "required": false,
            "schema": {
              "default": false,
              "type": "boolean"
            }
          },
          {
            "description": "Filter by analysis type (defaults to journal_entry)",
            "in": "query",
            "name": "analysis_type",
            "required": false,
            "schema": {
              "enum": [
                "categorization",
                "journal_entry",
                "document_match",
                "rule_suggestion"
              ],
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GetAnalysisResponse"
                }
              }
            },
            "description": "Analysis retrieved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get previous AI analysis for a transaction",
        "tags": [
          "AI Reconciliation"
        ]
      }
    },
    "/api/ai-reconciliation/history-suggestion/{transactionId}": {
      "get": {
        "description": "Proposes the journal the tenant booked the last time a bank row with the same\ndescription key appeared (承認番号 / TID / 納付番号 stripped). Deterministic: a same-amount\nprior entry is copied line for line; otherwise a single account used by ≥ 80 % of prior\nentries is proposed for the full amount; anything less decisive is `{ found: false }`.\nNo LLM call, no AI rate limit. The same logic runs first inside\n`POST /generate-journal-entry-simple`, where an indecisive history becomes a prompt hint.",
        "parameters": [
          {
            "in": "path",
            "name": "transactionId",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "basis": {
                          "nullable": true,
                          "properties": {
                            "basis": {
                              "enum": [
                                "same_amount",
                                "single_account"
                              ],
                              "type": "string"
                            },
                            "latestEntryDate": {
                              "description": "YYYYMMDD",
                              "type": "integer"
                            },
                            "latestEntryNumber": {
                              "type": "string"
                            },
                            "matches": {
                              "type": "integer"
                            }
                          },
                          "type": "object"
                        },
                        "found": {
                          "type": "boolean"
                        },
                        "historyCount": {
                          "description": "Prior posted entries on the same description key",
                          "type": "integer"
                        },
                        "suggestion": {
                          "description": "Same shape as the generate-journal-entry-simple response",
                          "nullable": true,
                          "type": "object"
                        }
                      },
                      "required": [
                        "found",
                        "historyCount"
                      ],
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Proposal or a miss"
          },
          "401": {
            "description": "未認証"
          },
          "404": {
            "description": "取引が見つからない"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "同じ摘要の過去の仕訳に基づく提案（AI不使用）",
        "tags": [
          "AI Reconciliation"
        ]
      }
    },
    "/api/ai/analyze-transaction": {
      "post": {
        "description": "Analyze a bank transaction using AI to suggest linkage type, matching documents, and account codes",
        "operationId": "analyzeTransaction",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AnalyzeTransactionRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/AnalyzeTransactionResponse"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Analysis complete"
          }
        },
        "summary": "AI transaction analysis",
        "tags": [
          "AI Analysis"
        ]
      }
    },
    "/api/ai/analyze-transactions/batch": {
      "post": {
        "description": "Analyze multiple transactions in one call for improved performance when viewing 100+ transactions",
        "operationId": "batchAnalyzeTransactions",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "includeDocumentMatches": {
                    "default": true,
                    "description": "Include matching documents (set false for faster response)",
                    "type": "boolean"
                  },
                  "transactionIds": {
                    "description": "Bank transaction IDs to analyze",
                    "items": {
                      "format": "uuid",
                      "type": "string"
                    },
                    "maxItems": 100,
                    "type": "array"
                  }
                },
                "required": [
                  "transactionIds"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "analyses": {
                          "additionalProperties": {
                            "$ref": "#/components/schemas/AnalyzeTransactionResponse"
                          },
                          "description": "Map of transactionId to analysis result",
                          "type": "object"
                        },
                        "count": {
                          "type": "integer"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Batch analysis complete"
          }
        },
        "summary": "Batch transaction analysis (Performance)",
        "tags": [
          "AI Analysis"
        ]
      }
    },
    "/api/ai/preferences": {
      "get": {
        "description": "Retrieve all AI preferences for the authenticated user with optional filtering and prompt preview",
        "parameters": [
          {
            "in": "query",
            "name": "preference_type",
            "schema": {
              "$ref": "#/components/schemas/AIPreferenceType"
            }
          },
          {
            "in": "query",
            "name": "scope",
            "schema": {
              "$ref": "#/components/schemas/AIPreferenceScope"
            }
          },
          {
            "in": "query",
            "name": "is_active",
            "schema": {
              "type": "boolean"
            }
          },
          {
            "description": "Include generated AI prompt preview",
            "in": "query",
            "name": "include_prompt_preview",
            "schema": {
              "type": "boolean"
            }
          },
          {
            "in": "query",
            "name": "page_size",
            "schema": {
              "default": 50,
              "maximum": 100,
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "page_number",
            "schema": {
              "default": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "items": {
                        "$ref": "#/components/schemas/AIPreference"
                      },
                      "type": "array"
                    },
                    "pagination": {
                      "properties": {
                        "page_number": {
                          "type": "integer"
                        },
                        "page_size": {
                          "type": "integer"
                        },
                        "total_items": {
                          "type": "integer"
                        },
                        "total_pages": {
                          "type": "integer"
                        }
                      },
                      "type": "object"
                    },
                    "prompt_preview": {
                      "description": "Generated AI prompt context",
                      "nullable": true,
                      "type": "string"
                    },
                    "stats": {
                      "$ref": "#/components/schemas/AIPreferencesStats"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "AI preferences retrieved successfully"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get user AI preferences",
        "tags": [
          "AI Preferences"
        ]
      },
      "post": {
        "description": "Create a new AI preference for journal generation",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateAIPreferenceRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/AIPreference"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Preference created successfully"
          },
          "401": {
            "description": "Unauthorized"
          },
          "409": {
            "description": "Preference with this pattern already exists"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create AI preference",
        "tags": [
          "AI Preferences"
        ]
      }
    },
    "/api/ai/preferences/feedback": {
      "get": {
        "description": "Retrieve history of AI corrections for the user",
        "parameters": [
          {
            "in": "query",
            "name": "limit",
            "schema": {
              "default": 50,
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "offset",
            "schema": {
              "default": 0,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Feedback history retrieved"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get feedback history",
        "tags": [
          "AI Preferences"
        ]
      },
      "post": {
        "description": "Record user correction to AI suggestion. Used for continuous learning.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AIFeedbackRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "id": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "preference_created_id": {
                          "description": "ID of auto-created preference if applicable",
                          "format": "uuid",
                          "nullable": true,
                          "type": "string"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Feedback recorded"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Record AI feedback",
        "tags": [
          "AI Preferences"
        ]
      }
    },
    "/api/ai/preferences/prompt-preview": {
      "get": {
        "description": "Get a preview of the AI prompt that would be generated from active preferences",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "prompt_preview": {
                          "description": "Generated AI prompt context",
                          "example": "## ユーザー設定: 取引先マッピング\n- AWS/Amazon Web Services → 通信費(6230)",
                          "type": "string"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Prompt preview generated"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Preview AI prompt context",
        "tags": [
          "AI Preferences"
        ]
      }
    },
    "/api/ai/preferences/seed-defaults": {
      "post": {
        "description": "Create default AI preferences for common Japanese business patterns",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "created_count": {
                          "example": 4,
                          "type": "integer"
                        },
                        "preferences": {
                          "items": {
                            "$ref": "#/components/schemas/AIPreference"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Defaults seeded successfully"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Seed default preferences",
        "tags": [
          "AI Preferences"
        ]
      }
    },
    "/api/ai/preferences/{preference_id}": {
      "delete": {
        "parameters": [
          {
            "in": "path",
            "name": "preference_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Preference deleted"
          },
          "404": {
            "description": "Preference not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Delete preference",
        "tags": [
          "AI Preferences"
        ]
      },
      "get": {
        "parameters": [
          {
            "in": "path",
            "name": "preference_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/AIPreference"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Preference retrieved"
          },
          "404": {
            "description": "Preference not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get single preference",
        "tags": [
          "AI Preferences"
        ]
      },
      "put": {
        "parameters": [
          {
            "in": "path",
            "name": "preference_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateAIPreferenceRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Preference updated"
          },
          "404": {
            "description": "Preference not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update preference",
        "tags": [
          "AI Preferences"
        ]
      }
    },
    "/api/auth/backup-email": {
      "delete": {
        "description": "Remove the backup email from the account",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "message": {
                      "example": "バックアップメールを削除しました",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Backup email removed"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Remove backup email",
        "tags": [
          "Auth Recovery"
        ]
      },
      "get": {
        "description": "Get the current backup email configuration for the authenticated user",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BackupEmailResponse"
                }
              }
            },
            "description": "Backup email status"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get backup email status",
        "tags": [
          "Auth Recovery"
        ]
      },
      "post": {
        "description": "Add or update the backup email address. Sends verification email.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AddBackupEmailRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "email": {
                          "example": "ba***@example.com",
                          "type": "string"
                        },
                        "isVerified": {
                          "example": false,
                          "type": "boolean"
                        },
                        "verificationSentAt": {
                          "format": "date-time",
                          "type": "string"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "確認メールを送信しました",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Verification email sent"
          },
          "400": {
            "description": "Validation error (same as primary email)"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Add backup email",
        "tags": [
          "Auth Recovery"
        ]
      }
    },
    "/api/auth/backup-email/resend": {
      "post": {
        "description": "Resend the backup email verification email",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "verificationSentAt": {
                          "format": "date-time",
                          "type": "string"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "確認メールを再送信しました",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Verification email resent"
          },
          "400": {
            "description": "No backup email set or already verified"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Resend verification email",
        "tags": [
          "Auth Recovery"
        ]
      }
    },
    "/api/auth/backup-email/verify": {
      "post": {
        "description": "Verify backup email using token from verification email",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/VerifyBackupEmailRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "email": {
                          "example": "ba***@example.com",
                          "type": "string"
                        },
                        "isVerified": {
                          "example": true,
                          "type": "boolean"
                        },
                        "verifiedAt": {
                          "format": "date-time",
                          "type": "string"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "バックアップメールを確認しました",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Email verified successfully"
          },
          "400": {
            "description": "Invalid or expired token"
          }
        },
        "summary": "Verify backup email",
        "tags": [
          "Auth Recovery"
        ]
      }
    },
    "/api/auth/recovery-codes": {
      "delete": {
        "description": "Delete all recovery codes for the account",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "message": {
                      "example": "リカバリーコードを削除しました",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Recovery codes deleted"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Delete recovery codes",
        "tags": [
          "Auth Recovery"
        ]
      }
    },
    "/api/auth/recovery-codes/generate": {
      "post": {
        "description": "Generate 8 new recovery codes. IMPORTANT: Codes are shown only once!",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/GenerateRecoveryCodesRequest"
              }
            }
          },
          "required": false
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GeneratedRecoveryCodesResponse"
                }
              }
            },
            "description": "Recovery codes generated"
          },
          "400": {
            "description": "Codes exist and confirm_regenerate not set"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Generate recovery codes",
        "tags": [
          "Auth Recovery"
        ]
      }
    },
    "/api/auth/recovery-codes/status": {
      "get": {
        "description": "Get the status of recovery codes (count, used, remaining)",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RecoveryCodesStatusResponse"
                }
              }
            },
            "description": "Recovery codes status"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get recovery codes status",
        "tags": [
          "Auth Recovery"
        ]
      }
    },
    "/api/auth/recovery/initiate": {
      "post": {
        "description": "Start the account recovery process. Returns available methods.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/InitiateRecoveryRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RecoveryMethodsResponse"
                }
              }
            },
            "description": "Recovery methods (always returns success)"
          }
        },
        "summary": "Initiate account recovery",
        "tags": [
          "Auth Recovery"
        ]
      }
    },
    "/api/auth/recovery/verify-code": {
      "post": {
        "description": "Verify a recovery code during account recovery",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/VerifyRecoveryCodeRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "nextAction": {
                          "example": "google_reauth",
                          "type": "string"
                        },
                        "remainingCodes": {
                          "type": "integer"
                        },
                        "warning": {
                          "nullable": true,
                          "type": "string"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Code verified - redirect to Google re-auth"
          },
          "401": {
            "description": "Invalid recovery code"
          }
        },
        "summary": "Verify recovery code",
        "tags": [
          "Auth Recovery"
        ]
      }
    },
    "/api/auth/security-score": {
      "get": {
        "description": "Get the user security score based on recovery setup",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SecurityScoreResponse"
                }
              }
            },
            "description": "Security score"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get security score",
        "tags": [
          "Auth Recovery"
        ]
      }
    },
    "/api/bank-accounts": {
      "get": {
        "description": "Returns all bank accounts for the authenticated user ordered by is_primary DESC, sort_order ASC. Supports optional balance stats and connection status enrichment.",
        "operationId": "listBankAccounts",
        "parameters": [
          {
            "description": "Filter by company ID",
            "in": "query",
            "name": "company_id",
            "required": false,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Filter by account purpose",
            "in": "query",
            "name": "purpose",
            "required": false,
            "schema": {
              "enum": [
                "business",
                "personal",
                "reimbursement",
                "loan",
                "savings",
                "tax_payment",
                "payroll",
                "deposit",
                "other"
              ],
              "type": "string"
            }
          },
          {
            "description": "Include latest balance stats per account (single aggregate query)",
            "in": "query",
            "name": "include_latest_balance",
            "required": false,
            "schema": {
              "type": "boolean"
            }
          },
          {
            "description": "Include API connection status from bank_connections",
            "in": "query",
            "name": "include_connection_status",
            "required": false,
            "schema": {
              "type": "boolean"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "items": {
                        "$ref": "#/components/schemas/BankAccountWithBalance"
                      },
                      "type": "array"
                    },
                    "message": {
                      "example": "Bank accounts retrieved successfully",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    },
                    "total": {
                      "example": 3,
                      "type": "integer"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Bank accounts retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List all bank accounts (v5.14+)",
        "tags": [
          "Bank Account Settings"
        ]
      },
      "post": {
        "description": "Creates a new bank account. First account per user+company is automatically set as primary. Director loan types validated against company entity_type.",
        "operationId": "createBankAccount",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateBankAccountRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BankAccountWithBalance"
                }
              }
            },
            "description": "Bank account created successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "409": {
            "description": "Duplicate bank account (ERR_4011)"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create new bank account (v5.14+)",
        "tags": [
          "Bank Account Settings"
        ]
      }
    },
    "/api/bank-accounts/{id}": {
      "delete": {
        "description": "Deletes a bank account. Fails if account has linked transactions (ERR_10020). Auto-promotes next account to primary if deleted was primary.",
        "operationId": "deleteBankAccount",
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Bank account deleted successfully"
          },
          "400": {
            "description": "Cannot delete account with linked transactions (ERR_10020)"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Bank account not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Delete bank account by ID (v5.14+)",
        "tags": [
          "Bank Account Settings"
        ]
      },
      "get": {
        "operationId": "getBankAccount",
        "parameters": [
          {
            "description": "Bank account ID",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "include_latest_balance",
            "required": false,
            "schema": {
              "type": "boolean"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BankAccountWithBalance"
                }
              }
            },
            "description": "Bank account retrieved"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Bank account not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get single bank account by ID (v5.14+)",
        "tags": [
          "Bank Account Settings"
        ]
      },
      "put": {
        "operationId": "updateBankAccount",
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateBankAccountRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BankAccountWithBalance"
                }
              }
            },
            "description": "Bank account updated"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Bank account not found (ERR_3009)"
          },
          "409": {
            "description": "Duplicate bank account (ERR_4011)"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update bank account by ID (v5.14+)",
        "tags": [
          "Bank Account Settings"
        ]
      }
    },
    "/api/credit-cards": {
      "get": {
        "description": "Get all registered credit cards for the authenticated user",
        "parameters": [
          {
            "description": "Filter by company ID",
            "in": "query",
            "name": "company_id",
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Include soft-deleted cards",
            "in": "query",
            "name": "include_inactive",
            "schema": {
              "default": false,
              "type": "boolean"
            }
          },
          {
            "description": "Number of results per page",
            "in": "query",
            "name": "limit",
            "schema": {
              "default": 20,
              "maximum": 100,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "description": "Pagination offset",
            "in": "query",
            "name": "offset",
            "schema": {
              "default": 0,
              "minimum": 0,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CreditCardListResponse"
                }
              }
            },
            "description": "Credit cards retrieved successfully"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List registered credit cards",
        "tags": [
          "Credit Cards"
        ]
      },
      "post": {
        "description": "Register a new credit card for the authenticated user",
        "requestBody": {
          "content": {
            "application/json": {
              "example": {
                "brand": "VISA",
                "card_name": "楽天カード（メイン）",
                "closing_day": 15,
                "color": "#e11d48",
                "issuer": "楽天カード株式会社",
                "last_four_digits": "1234",
                "payment_day": 10
              },
              "schema": {
                "$ref": "#/components/schemas/CreateCreditCardRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/RegisteredCreditCard"
                    },
                    "message": {
                      "example": "Credit card registered successfully",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Credit card registered successfully"
          },
          "400": {
            "description": "Invalid request body"
          },
          "401": {
            "description": "Unauthorized"
          },
          "409": {
            "description": "Card with same last 4 digits already exists"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Register a new credit card",
        "tags": [
          "Credit Cards"
        ]
      }
    },
    "/api/credit-cards/{id}": {
      "delete": {
        "description": "Soft delete a credit card (sets is_active = false)",
        "parameters": [
          {
            "description": "Credit card UUID",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "type": "null"
                    },
                    "message": {
                      "example": "Credit card deleted successfully",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Credit card deleted successfully"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Credit card not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Delete credit card",
        "tags": [
          "Credit Cards"
        ]
      },
      "get": {
        "description": "Get a single credit card by ID",
        "parameters": [
          {
            "description": "Credit card UUID",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/RegisteredCreditCard"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Credit card retrieved successfully"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Credit card not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get credit card by ID",
        "tags": [
          "Credit Cards"
        ]
      },
      "patch": {
        "description": "Update a credit card (partial update supported)",
        "parameters": [
          {
            "description": "Credit card UUID",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "example": {
                "card_name": "楽天カード（サブ）",
                "payment_day": 27
              },
              "schema": {
                "$ref": "#/components/schemas/UpdateCreditCardRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/RegisteredCreditCard"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Credit card updated successfully"
          },
          "400": {
            "description": "Invalid request body"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Credit card not found"
          },
          "409": {
            "description": "Card with same last 4 digits already exists"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update credit card",
        "tags": [
          "Credit Cards"
        ]
      }
    },
    "/api/credit-cards/{id}/restore": {
      "post": {
        "description": "Restore a soft-deleted credit card (sets is_active = true)",
        "parameters": [
          {
            "description": "Credit card UUID",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/RegisteredCreditCard"
                    },
                    "message": {
                      "example": "Credit card restored successfully",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Credit card restored successfully"
          },
          "400": {
            "description": "Card is already active"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Credit card not found"
          },
          "409": {
            "description": "Cannot restore: card with same last 4 digits is already active"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Restore deleted credit card",
        "tags": [
          "Credit Cards"
        ]
      }
    },
    "/api/documents/search-for-matching": {
      "get": {
        "description": "Smart search for documents that could match a bank transaction based on amount, date, and description",
        "operationId": "searchDocumentsForMatching",
        "parameters": [
          {
            "description": "Transaction amount to match",
            "in": "query",
            "name": "amount",
            "required": true,
            "schema": {
              "type": "number"
            }
          },
          {
            "description": "Transaction date YYYY-MM-DD",
            "in": "query",
            "name": "date",
            "required": true,
            "schema": {
              "format": "date",
              "type": "string"
            }
          },
          {
            "description": "Amount tolerance as decimal (0.05 = 5%)",
            "in": "query",
            "name": "amountTolerance",
            "schema": {
              "default": 0.05,
              "maximum": 1,
              "minimum": 0,
              "type": "number"
            }
          },
          {
            "description": "Days before/after to search",
            "in": "query",
            "name": "dateRangeDays",
            "schema": {
              "default": 7,
              "maximum": 90,
              "minimum": 0,
              "type": "integer"
            }
          },
          {
            "description": "Transaction description for vendor matching",
            "in": "query",
            "name": "description",
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "Comma-separated LinkableDocumentType values (e.g. receipt,invoice)",
            "in": "query",
            "name": "documentTypes",
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "Exclude already linked documents",
            "in": "query",
            "name": "excludeLinked",
            "schema": {
              "default": true,
              "type": "boolean"
            }
          },
          {
            "description": "Whether transaction is a deposit",
            "in": "query",
            "name": "isDeposit",
            "schema": {
              "type": "boolean"
            }
          },
          {
            "in": "query",
            "name": "limit",
            "schema": {
              "default": 20,
              "maximum": 100,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/DocumentSearchResponse"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Documents found"
          },
          "400": {
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetails"
                }
              }
            },
            "description": "Validation failed: amount/date missing or not parseable, or an option out of range (limit 1–100, dateRangeDays 0–90, amountTolerance 0–1, unknown document type, non-boolean flag). Rejected, never clamped."
          }
        },
        "summary": "Search documents for matching",
        "tags": [
          "Document Search"
        ]
      }
    },
    "/api/employees": {
      "get": {
        "description": "List employees with filtering and pagination",
        "parameters": [
          {
            "in": "query",
            "name": "company_id",
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "position_type",
            "schema": {
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "employment_status",
            "schema": {
              "enum": [
                "active",
                "on_leave",
                "retired",
                "pending_start"
              ],
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "is_director",
            "schema": {
              "type": "boolean"
            }
          },
          {
            "in": "query",
            "name": "search",
            "schema": {
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "page",
            "schema": {
              "default": 1,
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "page_size",
            "schema": {
              "default": 20,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Employee list"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List employees",
        "tags": [
          "Employees"
        ]
      },
      "post": {
        "description": "Create a new employee record. For 一人社長, the owner is typically registered as a director.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateEmployeeInput"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "description": "Employee created successfully"
          },
          "409": {
            "description": "Employee number already exists"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create employee",
        "tags": [
          "Employees"
        ]
      }
    },
    "/api/employees/dependents/{dependent_id}": {
      "delete": {
        "parameters": [
          {
            "in": "path",
            "name": "dependent_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Dependent deleted"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Delete dependent",
        "tags": [
          "Employees"
        ]
      },
      "put": {
        "parameters": [
          {
            "in": "path",
            "name": "dependent_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateDependentInput"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Dependent updated"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update dependent",
        "tags": [
          "Employees"
        ]
      }
    },
    "/api/employees/hotei-chosho/{year}": {
      "get": {
        "description": "Calculate salary section of 法定調書合計表 with role-based thresholds",
        "parameters": [
          {
            "in": "path",
            "name": "year",
            "required": true,
            "schema": {
              "example": 2025,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "法定調書 calculation result"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Calculate 法定調書合計表",
        "tags": [
          "Employees"
        ]
      }
    },
    "/api/employees/submission-required/{year}": {
      "get": {
        "description": "Get employees whose 源泉徴収票 must be submitted to tax office",
        "parameters": [
          {
            "in": "path",
            "name": "year",
            "required": true,
            "schema": {
              "example": 2025,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Employees requiring submission"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get employees requiring submission",
        "tags": [
          "Employees"
        ]
      }
    },
    "/api/employees/{employee_id}": {
      "delete": {
        "parameters": [
          {
            "in": "path",
            "name": "employee_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Employee deleted"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Delete employee",
        "tags": [
          "Employees"
        ]
      },
      "get": {
        "parameters": [
          {
            "in": "path",
            "name": "employee_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Employee details"
          },
          "404": {
            "description": "Employee not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get employee",
        "tags": [
          "Employees"
        ]
      },
      "put": {
        "parameters": [
          {
            "in": "path",
            "name": "employee_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateEmployeeInput"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Employee updated"
          },
          "404": {
            "description": "Employee not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update employee",
        "tags": [
          "Employees"
        ]
      }
    },
    "/api/employees/{employee_id}/dependents": {
      "get": {
        "parameters": [
          {
            "in": "path",
            "name": "employee_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Dependent list"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List dependents",
        "tags": [
          "Employees"
        ]
      },
      "post": {
        "description": "Add a dependent (扶養家族) to an employee",
        "parameters": [
          {
            "in": "path",
            "name": "employee_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateDependentInput"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "description": "Dependent added"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Add dependent",
        "tags": [
          "Employees"
        ]
      }
    },
    "/api/employees/{employee_id}/insurance": {
      "post": {
        "description": "Record monthly social insurance premium",
        "parameters": [
          {
            "in": "path",
            "name": "employee_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/InsurancePremiumInput"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Insurance premium recorded"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Record insurance premium",
        "tags": [
          "Employees"
        ]
      }
    },
    "/api/expense-wizard/categorize": {
      "post": {
        "description": "Get category suggestion for a single expense item",
        "operationId": "categorizeExpense",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CategorizeRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/CategorizationResult"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Categorization result"
          }
        },
        "summary": "Categorize expense",
        "tags": [
          "Expense Category Rules"
        ]
      }
    },
    "/api/expense-wizard/categorize/batch": {
      "post": {
        "description": "Get category suggestions for multiple expense items (max 100)",
        "operationId": "batchCategorizeExpenses",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/BatchCategorizeRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "results": {
                          "items": {
                            "properties": {
                              "categoryName": {
                                "type": "string"
                              },
                              "confidence": {
                                "type": "number"
                              },
                              "itemId": {
                                "type": "string"
                              },
                              "matchedRuleId": {
                                "nullable": true,
                                "type": "string"
                              },
                              "source": {
                                "$ref": "#/components/schemas/SuggestionSource"
                              },
                              "suggestedCategory": {
                                "type": "integer"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Batch categorization results"
          },
          "400": {
            "description": "Invalid input (empty items or > 100 items)"
          }
        },
        "summary": "Batch categorize expenses",
        "tags": [
          "Expense Category Rules"
        ]
      }
    },
    "/api/expense-wizard/category-corrections": {
      "post": {
        "description": "Record a user correction for learning. The system may auto-create user rules based on repeated corrections.",
        "operationId": "recordCategoryCorrection",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/RecordCorrectionRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/CorrectionRecordedResponse"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Correction recorded"
          },
          "400": {
            "description": "Invalid input (same suggested and corrected category)"
          }
        },
        "summary": "Record category correction",
        "tags": [
          "Expense Category Rules"
        ]
      }
    },
    "/api/expense-wizard/category-rules": {
      "get": {
        "description": "Get all active category rules (system + user's own)",
        "operationId": "listCategoryRules",
        "parameters": [
          {
            "in": "query",
            "name": "rule_type",
            "schema": {
              "$ref": "#/components/schemas/CategoryRuleType"
            }
          },
          {
            "in": "query",
            "name": "category",
            "schema": {
              "maximum": 26,
              "minimum": 0,
              "type": "integer"
            }
          },
          {
            "description": "Search in pattern or rule name",
            "in": "query",
            "name": "search",
            "schema": {
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "include_system",
            "schema": {
              "default": true,
              "type": "boolean"
            }
          },
          {
            "in": "query",
            "name": "page_size",
            "schema": {
              "default": 100,
              "maximum": 500,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "page_number",
            "schema": {
              "default": 1,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "pagination": {
                          "properties": {
                            "pageNumber": {
                              "type": "integer"
                            },
                            "pageSize": {
                              "type": "integer"
                            },
                            "totalPages": {
                              "type": "integer"
                            }
                          },
                          "type": "object"
                        },
                        "rules": {
                          "items": {
                            "$ref": "#/components/schemas/CategoryRule"
                          },
                          "type": "array"
                        },
                        "systemCount": {
                          "type": "integer"
                        },
                        "total": {
                          "type": "integer"
                        },
                        "userCount": {
                          "type": "integer"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Category rules retrieved"
          }
        },
        "summary": "List category rules",
        "tags": [
          "Expense Category Rules"
        ]
      },
      "post": {
        "description": "Create a new user-specific category rule",
        "operationId": "createCategoryRule",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateCategoryRuleRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "rule": {
                          "$ref": "#/components/schemas/CategoryRule"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Rule created"
          },
          "409": {
            "description": "Duplicate rule pattern exists"
          }
        },
        "summary": "Create category rule",
        "tags": [
          "Expense Category Rules"
        ]
      }
    },
    "/api/expense-wizard/category-rules/suppressed": {
      "get": {
        "description": "System rules this user turned off from a wizard card (DELETE on a system rule), newest first. Each can be turned back on with POST …/{rule_id}/restore.",
        "operationId": "listSuppressedCategoryRules",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "rules": {
                          "items": {
                            "properties": {
                              "category": {
                                "example": 21,
                                "type": "integer"
                              },
                              "categoryName": {
                                "example": "新聞図書費",
                                "type": "string"
                              },
                              "pattern": {
                                "example": "本",
                                "type": "string"
                              },
                              "ruleId": {
                                "format": "uuid",
                                "type": "string"
                              },
                              "ruleType": {
                                "enum": [
                                  "vendor",
                                  "keyword",
                                  "combined"
                                ],
                                "type": "string"
                              },
                              "suppressedAt": {
                                "format": "date-time",
                                "type": "string"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Suppressed system rules"
          }
        },
        "summary": "List system rules the user turned off",
        "tags": [
          "Expense Category Rules"
        ]
      }
    },
    "/api/expense-wizard/category-rules/{rule_id}": {
      "delete": {
        "description": "Delete one of the user's category rules (soft delete). On a system rule — shared by everyone and never edited — it turns that rule off for this user only (expense_category_rule_suppressions).",
        "operationId": "deleteCategoryRule",
        "parameters": [
          {
            "in": "path",
            "name": "rule_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Rule deleted"
          },
          "404": {
            "description": "Rule not found or cannot be deleted"
          }
        },
        "summary": "Delete category rule",
        "tags": [
          "Expense Category Rules"
        ]
      },
      "get": {
        "description": "Get a single category rule by ID",
        "operationId": "getCategoryRule",
        "parameters": [
          {
            "in": "path",
            "name": "rule_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "rule": {
                          "$ref": "#/components/schemas/CategoryRule"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Rule retrieved"
          },
          "404": {
            "description": "Rule not found"
          }
        },
        "summary": "Get category rule",
        "tags": [
          "Expense Category Rules"
        ]
      },
      "patch": {
        "description": "Update a user's category rule (cannot modify system rules)",
        "operationId": "updateCategoryRule",
        "parameters": [
          {
            "in": "path",
            "name": "rule_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateCategoryRuleRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "rule": {
                          "$ref": "#/components/schemas/CategoryRule"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Rule updated"
          },
          "404": {
            "description": "Rule not found or cannot be modified"
          }
        },
        "summary": "Update category rule",
        "tags": [
          "Expense Category Rules"
        ]
      }
    },
    "/api/expense-wizard/category-rules/{rule_id}/restore": {
      "post": {
        "description": "Undo of DELETE on a system rule: the rule applies to this user again.",
        "operationId": "restoreCategoryRule",
        "parameters": [
          {
            "in": "path",
            "name": "rule_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Rule turned back on"
          },
          "400": {
            "description": "rule_id is not a UUID"
          },
          "404": {
            "description": "This rule is not turned off for the user"
          }
        },
        "summary": "Turn a system rule back on",
        "tags": [
          "Expense Category Rules"
        ]
      }
    },
    "/api/expense-wizard/detect-anomalies": {
      "post": {
        "description": "Detect anomalies in expense items (duplicates, high amounts, etc.).",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "items": {
                    "items": {
                      "properties": {
                        "amount": {
                          "type": "number"
                        },
                        "category": {
                          "type": "integer"
                        },
                        "date": {
                          "format": "date",
                          "type": "string"
                        },
                        "description": {
                          "type": "string"
                        },
                        "id": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "vendor": {
                          "type": "string"
                        }
                      },
                      "required": [
                        "id",
                        "amount",
                        "category"
                      ],
                      "type": "object"
                    },
                    "maxItems": 50,
                    "minItems": 1,
                    "type": "array"
                  },
                  "session_id": {
                    "format": "uuid",
                    "type": "string"
                  }
                },
                "required": [
                  "items"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "anomalies": {
                          "type": "array"
                        },
                        "overall_risk_score": {
                          "type": "number"
                        },
                        "summary": {
                          "properties": {
                            "by_severity": {
                              "type": "object"
                            },
                            "by_type": {
                              "type": "object"
                            },
                            "total_anomalies": {
                              "type": "integer"
                            }
                          },
                          "type": "object"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Detection completed"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Detect anomalies",
        "tags": [
          "Expense Wizard"
        ]
      }
    },
    "/api/expense-wizard/fare-routes": {
      "get": {
        "description": "Remembered routes: the newest fare line per station pair (either direction), up to 20.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "items": {
                        "$ref": "#/components/schemas/WizardFareRoute"
                      },
                      "type": "array"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Past sections, newest first"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "The owner's past fare sections",
        "tags": [
          "Expense Wizard"
        ]
      }
    },
    "/api/expense-wizard/items/{item_id}": {
      "delete": {
        "description": "Remove an item from its session. A soft delete: `POST /items/{item_id}/restore` brings it back. 409 once the session is finished.",
        "parameters": [
          {
            "in": "path",
            "name": "item_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Item deleted successfully"
          },
          "404": {
            "description": "Item not found"
          },
          "409": {
            "description": "The session is completed, being created or cancelled"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Delete item",
        "tags": [
          "Expense Wizard"
        ]
      },
      "patch": {
        "description": "Update item data (user corrections to AI analysis).",
        "parameters": [
          {
            "in": "path",
            "name": "item_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "dismissed_anomalies": {
                    "items": {
                      "format": "uuid",
                      "type": "string"
                    },
                    "type": "array"
                  },
                  "extracted_amount": {
                    "minimum": 0,
                    "type": "number"
                  },
                  "extracted_date": {
                    "format": "date",
                    "type": "string"
                  },
                  "extracted_description": {
                    "maxLength": 2000,
                    "type": "string"
                  },
                  "extracted_vendor": {
                    "maxLength": 500,
                    "type": "string"
                  },
                  "lodging_cap_exception": {
                    "description": "The owner's reason for booking this lodging above the 出張規程 cap; null or empty = it books at the cap.",
                    "maxLength": 200,
                    "nullable": true,
                    "type": "string"
                  },
                  "lodging_nights": {
                    "description": "Nights a lodging receipt covers (the 出張規程 cap is per night); 0 = not lodging, null = from the receipt.",
                    "maximum": 60,
                    "minimum": 0,
                    "nullable": true,
                    "type": "integer"
                  },
                  "party_size": {
                    "description": "People the receipt paid for. The claim books the traveller's share floor(amount / party_size); null or 1 = not shared.",
                    "maximum": 20,
                    "minimum": 1,
                    "nullable": true,
                    "type": "integer"
                  },
                  "payment_method": {
                    "enum": [
                      "cash",
                      "personal_card",
                      "corporate_card",
                      "bank_transfer"
                    ],
                    "type": "string"
                  },
                  "suggested_category": {
                    "maximum": 26,
                    "minimum": 0,
                    "type": "integer"
                  },
                  "tax_amount": {
                    "minimum": 0,
                    "type": "number"
                  },
                  "tax_type": {
                    "enum": [
                      0,
                      8,
                      10
                    ],
                    "type": "integer"
                  },
                  "user_notes": {
                    "maxLength": 1000,
                    "type": "string"
                  }
                },
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Item updated successfully"
          },
          "404": {
            "description": "Item not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update item",
        "tags": [
          "Expense Wizard"
        ]
      }
    },
    "/api/expense-wizard/items/{item_id}/reread": {
      "delete": {
        "description": "Remove a ready or failed re-read; the current reading stays. A re-read still running is left alone.",
        "parameters": [
          {
            "in": "path",
            "name": "item_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "discarded": {
                          "type": "boolean"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Whether a result was dropped"
          },
          "404": {
            "description": "Item not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Drop a re-read",
        "tags": [
          "Expense Wizard"
        ]
      }
    },
    "/api/expense-wizard/items/{item_id}/reread/apply": {
      "post": {
        "description": "Write a ready re-read onto the item. Without overwrite_edited the owner's edited fields stay (kept_fields lists them); with it, the re-read replaces them and clears the owner's category choice.",
        "parameters": [
          {
            "in": "path",
            "name": "item_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "overwrite_edited": {
                    "default": false,
                    "type": "boolean"
                  }
                },
                "type": "object"
              }
            }
          }
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "item": {
                          "$ref": "#/components/schemas/WizardItem"
                        },
                        "kept_fields": {
                          "items": {
                            "type": "string"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Applied"
          },
          "404": {
            "description": "Item not found"
          },
          "409": {
            "description": "No ready re-read, a finished session, or the item changed meanwhile"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Apply a re-read",
        "tags": [
          "Expense Wizard"
        ]
      }
    },
    "/api/expense-wizard/items/{item_id}/restore": {
      "post": {
        "description": "The review step's 元に戻す after 削除. Refused for the earlier file of a replaced receipt and for a finished or discarded session.",
        "parameters": [
          {
            "in": "path",
            "name": "item_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/WizardItem"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "The restored item"
          },
          "404": {
            "description": "Item not found"
          },
          "409": {
            "description": "Replaced-file history, or a finished session"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Restore a removed item",
        "tags": [
          "Expense Wizard"
        ]
      }
    },
    "/api/expense-wizard/sessions": {
      "get": {
        "description": "Get paginated list of user's expense wizard sessions, newest activity first. Without `status` or `include_completed`, returns the open sessions: in progress plus `failed` (a create that can be retried). Each row carries `lifecycle` (idle, counted toward the limit, analysis stalled, discardable, item progress); `limit` carries the cap and how many sessions count now.",
        "parameters": [
          {
            "in": "query",
            "name": "page_size",
            "schema": {
              "default": 20,
              "maximum": 100,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "page_number",
            "schema": {
              "default": 1,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "status",
            "schema": {
              "enum": [
                "draft",
                "analyzing",
                "reviewed",
                "creating",
                "completed",
                "failed",
                "cancelled"
              ],
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "include_completed",
            "schema": {
              "default": false,
              "type": "boolean"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "items": {
                          "items": {
                            "$ref": "#/components/schemas/WizardSession"
                          },
                          "type": "array"
                        },
                        "limit": {
                          "properties": {
                            "active_count": {
                              "example": 2,
                              "type": "integer"
                            },
                            "idle_after_days": {
                              "example": 14,
                              "type": "integer"
                            },
                            "max_active": {
                              "example": 5,
                              "type": "integer"
                            }
                          },
                          "type": "object"
                        },
                        "pagination": {
                          "$ref": "#/components/schemas/Pagination"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Sessions retrieved successfully"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List user sessions",
        "tags": [
          "Expense Wizard"
        ]
      },
      "post": {
        "description": "\nCreates a new expense wizard session for streamlined expense reimbursement workflow.\n\n**Session limit (2026-09-25, docs/adr-expense-wizard-journey.md):**\n- At most 5 in-progress sessions (`draft` / `analyzing` / `reviewed` / `creating`) count toward the limit\n- A session with no write to it or its items for 14 days is idle: listed, never counted; any write makes it active again\n- Completed, failed and cancelled sessions never count\n- At the limit, the 429 carries `existing_sessions` (each with `lifecycle`) so the client shows the list to resume or discard\n- `force_cleanup: true` still cancels the oldest counted draft older than 24h\n\n**Frontend Best Practice:**\n```typescript\n// 1. Check existing sessions before creating new\nconst { data } = await api.get('/api/expense-wizard/sessions?status=draft');\nif (data.items.length > 0) {\n  // Resume existing or show session manager UI\n}\n\n// 2. Or use force_cleanup for automatic handling\nawait api.post('/api/expense-wizard/sessions', {\n  trip_type: 'travel',\n  force_cleanup: true  // Auto-cancel stale drafts\n});\n```\n\n**Trip Types:**\n- `travel`: Business trip with itinerary, daily allowance\n- `reimbursement`: General expense reimbursement\n- `other`: Custom workflow\n\n**Document Types (selected_doc_types):**\n- `travel`: 出張報告書 (Travel Report)\n- `claims`: 立替経費精算書 (Expense Claims)\n- `salary_slip`: 給与明細書 (Salary Slip)\n- `payment`: 支払明細書 (Payment Statement)\n      ",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "basic": {
                  "summary": "Basic session creation",
                  "value": {
                    "selected_doc_types": [
                      "claims",
                      "travel"
                    ],
                    "trip_type": "travel"
                  }
                },
                "with_force_cleanup": {
                  "summary": "With auto-cleanup for dev/testing",
                  "value": {
                    "force_cleanup": true,
                    "trip_type": "travel"
                  }
                }
              },
              "schema": {
                "properties": {
                  "force_cleanup": {
                    "default": false,
                    "description": "v5.4: Auto-cancel oldest stale draft session (>24h old) if at limit. Use for dev/testing to avoid manual cleanup.",
                    "type": "boolean"
                  },
                  "selected_doc_types": {
                    "default": [
                      "claims"
                    ],
                    "example": [
                      "travel",
                      "claims",
                      "salary_slip",
                      "payment"
                    ],
                    "items": {
                      "enum": [
                        "travel",
                        "claims",
                        "salary_slip",
                        "payment"
                      ],
                      "type": "string"
                    },
                    "type": "array"
                  },
                  "trip_info": {
                    "description": "Trip details (for travel type)",
                    "properties": {
                      "checklist": {
                        "description": "Answers to the pre-create trip checklist; merged onto the stored trip_info",
                        "items": {
                          "properties": {
                            "code": {
                              "enum": [
                                "LODGING",
                                "COMPANIONS",
                                "LATE_RETURN",
                                "HIGHWAY_TOLLS",
                                "COMMUTE_LEGS",
                                "TRAINING_CERTIFICATE",
                                "TAXI_RECEIPTS",
                                "TRAIN_FARES",
                                "ENTERTAINMENT_ATTENDEES"
                              ],
                              "type": "string"
                            },
                            "note": {
                              "maxLength": 500,
                              "type": "string"
                            },
                            "resolution": {
                              "enum": [
                                "answered",
                                "acknowledged",
                                "not_applicable"
                              ],
                              "type": "string"
                            }
                          },
                          "required": [
                            "code",
                            "resolution"
                          ],
                          "type": "object"
                        },
                        "type": "array"
                      },
                      "claim_title": {
                        "description": "The owner's name for the claim (confirmation step); the subject of every stored document name. Empty derives one.",
                        "maxLength": 60,
                        "type": "string"
                      },
                      "count_arrival_day": {
                        "description": "Whether that after-midnight arrival day earns 日当 (the owner decides; unanswered = not counted)",
                        "type": "boolean"
                      },
                      "daily_allowance": {
                        "description": "日当 per day the owner typed. Paid over the 規程 rate only with daily_allowance_user_set: true; otherwise read only when the 規程 has no rate for the trip category.",
                        "example": 4000,
                        "minimum": 0,
                        "type": "number"
                      },
                      "daily_allowance_user_set": {
                        "description": "True when the owner typed daily_allowance (the preflight then warns ALLOWANCE_RATE_NOT_FROM_RULES). false hands the rate back to the 規程.",
                        "type": "boolean"
                      },
                      "destination": {
                        "example": "高原拠点",
                        "type": "string"
                      },
                      "end_date": {
                        "example": "2025-12-21",
                        "format": "date",
                        "type": "string"
                      },
                      "purpose": {
                        "example": "リフォーム管理",
                        "type": "string"
                      },
                      "return_time": {
                        "description": "帰着時刻",
                        "example": "00:05",
                        "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$",
                        "type": "string"
                      },
                      "returned_after_midnight": {
                        "description": "The traveller got back after midnight, on the day after end_date",
                        "type": "boolean"
                      },
                      "start_date": {
                        "example": "2025-12-17",
                        "format": "date",
                        "type": "string"
                      }
                    },
                    "type": "object"
                  },
                  "trip_type": {
                    "default": "travel",
                    "description": "Type of expense workflow",
                    "enum": [
                      "travel",
                      "reimbursement",
                      "other"
                    ],
                    "type": "string"
                  }
                },
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "created_at": {
                          "format": "date-time",
                          "type": "string"
                        },
                        "id": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "selected_doc_types": {
                          "items": {
                            "type": "string"
                          },
                          "type": "array"
                        },
                        "status": {
                          "example": "draft",
                          "type": "string"
                        },
                        "trip_type": {
                          "example": "travel",
                          "type": "string"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Wizard session created successfully",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Session created successfully"
          },
          "429": {
            "content": {
              "application/json": {
                "example": {
                  "data": {
                    "existing_sessions": [
                      {
                        "created_at": "2026-01-29T10:00:00Z",
                        "id": "550e8400-e29b-41d4-a716-446655440001",
                        "is_stale": true,
                        "item_count": 3,
                        "status": "draft",
                        "trip_type": "travel",
                        "updated_at": "2026-01-29T10:30:00Z"
                      },
                      {
                        "created_at": "2026-01-30T14:00:00Z",
                        "id": "550e8400-e29b-41d4-a716-446655440002",
                        "is_stale": false,
                        "item_count": 5,
                        "status": "reviewed",
                        "trip_type": "reimbursement",
                        "updated_at": "2026-01-30T15:00:00Z"
                      }
                    ],
                    "max_sessions": 5,
                    "stale_threshold_hours": 24,
                    "suggestions": [
                      "Resume an existing draft session instead of creating new",
                      "Delete old sessions via DELETE /api/expense-wizard/sessions/:id",
                      "Set force_cleanup: true to auto-cancel oldest stale draft (>24h old)"
                    ]
                  },
                  "message": "Maximum active sessions (5) reached. Please complete or cancel existing sessions.",
                  "success": false
                },
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "existing_sessions": {
                          "description": "List of existing active sessions for UI management",
                          "items": {
                            "properties": {
                              "created_at": {
                                "format": "date-time",
                                "type": "string"
                              },
                              "id": {
                                "format": "uuid",
                                "type": "string"
                              },
                              "is_stale": {
                                "description": "True if session is older than 24 hours",
                                "type": "boolean"
                              },
                              "item_count": {
                                "description": "Number of items in session",
                                "type": "integer"
                              },
                              "status": {
                                "enum": [
                                  "draft",
                                  "analyzing",
                                  "reviewed",
                                  "creating"
                                ],
                                "type": "string"
                              },
                              "trip_type": {
                                "type": "string"
                              },
                              "updated_at": {
                                "format": "date-time",
                                "type": "string"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        },
                        "max_sessions": {
                          "example": 5,
                          "type": "integer"
                        },
                        "retry_after_seconds": {
                          "description": "Matches Retry-After header",
                          "example": 60,
                          "type": "integer"
                        },
                        "stale_threshold_hours": {
                          "example": 24,
                          "type": "integer"
                        },
                        "suggestions": {
                          "example": [
                            "Resume an existing draft session instead of creating new",
                            "Delete old sessions via DELETE /api/expense-wizard/sessions/:id",
                            "Set force_cleanup: true to auto-cancel oldest stale draft (>24h old)"
                          ],
                          "items": {
                            "type": "string"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Maximum active sessions (5) reached. Please complete or cancel existing sessions.",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Maximum active sessions (5) reached",
            "headers": {
              "Retry-After": {
                "description": "Seconds to wait before retrying (RFC 6585 compliant)",
                "schema": {
                  "example": 60,
                  "type": "integer"
                }
              },
              "X-RateLimit-Limit": {
                "description": "Maximum sessions allowed",
                "schema": {
                  "example": 5,
                  "type": "integer"
                }
              },
              "X-RateLimit-Remaining": {
                "description": "Sessions remaining (0 when limit reached)",
                "schema": {
                  "example": 0,
                  "type": "integer"
                }
              }
            }
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create new wizard session",
        "tags": [
          "Expense Wizard"
        ]
      }
    },
    "/api/expense-wizard/sessions/discard-idle": {
      "post": {
        "description": "Soft-cancel the sessions the owner picked under 長期間操作のない作業. Each is re-checked: a session touched since the list loaded, or one that cannot be discarded, is skipped with a reason.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "session_ids": {
                    "items": {
                      "format": "uuid",
                      "type": "string"
                    },
                    "maxItems": 50,
                    "minItems": 1,
                    "type": "array"
                  }
                },
                "required": [
                  "session_ids"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "discarded": {
                          "items": {
                            "format": "uuid",
                            "type": "string"
                          },
                          "type": "array"
                        },
                        "skipped": {
                          "items": {
                            "properties": {
                              "reason": {
                                "enum": [
                                  "not_found",
                                  "not_idle",
                                  "cannot_discard"
                                ],
                                "type": "string"
                              },
                              "session_id": {
                                "format": "uuid",
                                "type": "string"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Discarded and skipped sessions"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Discard idle sessions",
        "tags": [
          "Expense Wizard"
        ]
      }
    },
    "/api/expense-wizard/sessions/{session_id}": {
      "delete": {
        "description": "Discards a session: status becomes `cancelled` and its items are soft-deleted (no longer counted, analysed or treated as duplicates of a re-upload). Nothing is hard-deleted. A completed session is refused (409): its documents exist and the bundle undo is the way back. A `creating` session is refused until it has had no write for 10 minutes (BL-685: a create abandoned by a dead process); after that it may be discarded like any open session.",
        "parameters": [
          {
            "in": "path",
            "name": "session_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "items_discarded": {
                          "type": "integer"
                        },
                        "status": {
                          "enum": [
                            "cancelled"
                          ],
                          "type": "string"
                        },
                        "success": {
                          "type": "boolean"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Session discarded"
          },
          "404": {
            "description": "Session not found"
          },
          "409": {
            "description": "Refused: documents were already created from this session (use the bundle undo), or it is `creating` with a write in the last 10 minutes (a create may still be running)"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Discard session (soft cancel)",
        "tags": [
          "Expense Wizard"
        ]
      },
      "get": {
        "description": "Get session details including all items and analysis summary.",
        "parameters": [
          {
            "in": "path",
            "name": "session_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "items": {
                          "items": {
                            "$ref": "#/components/schemas/WizardItem"
                          },
                          "type": "array"
                        },
                        "session": {
                          "$ref": "#/components/schemas/WizardSession"
                        },
                        "summary": {
                          "properties": {
                            "completed_analysis": {
                              "type": "integer"
                            },
                            "critical_anomalies": {
                              "type": "integer"
                            },
                            "failed_analysis": {
                              "type": "integer"
                            },
                            "pending_analysis": {
                              "type": "integer"
                            },
                            "total_anomalies": {
                              "type": "integer"
                            }
                          },
                          "type": "object"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Session retrieved successfully"
          },
          "404": {
            "description": "Session not found or access denied"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get session with items",
        "tags": [
          "Expense Wizard"
        ]
      },
      "patch": {
        "description": "Update session configuration (trip type, info, document types). `trip_info` is merged onto the stored value (keys left out keep their stored value; `null` clears it).",
        "parameters": [
          {
            "in": "path",
            "name": "session_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "selected_doc_types": {
                    "items": {
                      "type": "string"
                    },
                    "type": "array"
                  },
                  "trip_info": {
                    "nullable": true,
                    "properties": {
                      "checklist": {
                        "description": "Answers to the pre-create trip checklist; merged onto the stored trip_info",
                        "items": {
                          "properties": {
                            "code": {
                              "enum": [
                                "LODGING",
                                "COMPANIONS",
                                "LATE_RETURN",
                                "HIGHWAY_TOLLS",
                                "COMMUTE_LEGS",
                                "TRAINING_CERTIFICATE",
                                "TAXI_RECEIPTS",
                                "TRAIN_FARES",
                                "ENTERTAINMENT_ATTENDEES"
                              ],
                              "type": "string"
                            },
                            "note": {
                              "maxLength": 500,
                              "type": "string"
                            },
                            "resolution": {
                              "enum": [
                                "answered",
                                "acknowledged",
                                "not_applicable"
                              ],
                              "type": "string"
                            }
                          },
                          "required": [
                            "code",
                            "resolution"
                          ],
                          "type": "object"
                        },
                        "type": "array"
                      },
                      "claim_title": {
                        "description": "The owner's name for the claim (confirmation step); the subject of every stored document name. Empty derives one.",
                        "maxLength": 60,
                        "type": "string"
                      },
                      "count_arrival_day": {
                        "description": "Whether that after-midnight arrival day earns 日当 (the owner decides; unanswered = not counted)",
                        "type": "boolean"
                      },
                      "daily_allowance": {
                        "description": "日当 per day the owner typed. Paid over the 規程 rate only with daily_allowance_user_set: true; otherwise read only when the 規程 has no rate for the trip category.",
                        "example": 4000,
                        "minimum": 0,
                        "type": "number"
                      },
                      "daily_allowance_user_set": {
                        "description": "True when the owner typed daily_allowance (the preflight then warns ALLOWANCE_RATE_NOT_FROM_RULES). false hands the rate back to the 規程.",
                        "type": "boolean"
                      },
                      "return_time": {
                        "description": "帰着時刻",
                        "example": "00:05",
                        "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$",
                        "type": "string"
                      },
                      "returned_after_midnight": {
                        "description": "The traveller got back after midnight, on the day after end_date",
                        "type": "boolean"
                      }
                    },
                    "type": "object"
                  },
                  "trip_type": {
                    "enum": [
                      "travel",
                      "reimbursement",
                      "other"
                    ],
                    "type": "string"
                  }
                },
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Session updated successfully"
          },
          "400": {
            "description": "Cannot update session in current status"
          },
          "404": {
            "description": "Session not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update session",
        "tags": [
          "Expense Wizard"
        ]
      }
    },
    "/api/expense-wizard/sessions/{session_id}/analysis-status": {
      "get": {
        "description": "Poll for analysis progress. Use for progress tracking.",
        "parameters": [
          {
            "in": "path",
            "name": "session_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "items": {
                          "description": "Each item carries `reread` (see WizardItemReread). A receipt being re-read reports `completed`: it keeps its earlier reading.",
                          "type": "array"
                        },
                        "progress": {
                          "properties": {
                            "completed": {
                              "type": "integer"
                            },
                            "failed": {
                              "type": "integer"
                            },
                            "pending": {
                              "type": "integer"
                            },
                            "total": {
                              "type": "integer"
                            }
                          },
                          "type": "object"
                        },
                        "status": {
                          "enum": [
                            "processing",
                            "completed"
                          ],
                          "type": "string"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Analysis status retrieved"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get analysis status",
        "tags": [
          "Expense Wizard"
        ]
      }
    },
    "/api/expense-wizard/sessions/{session_id}/analyze": {
      "post": {
        "description": "\nTrigger AI analysis for session items. Uses a **multi-layered extraction strategy**:\n\n**1. Filename Extraction (Always Available)**\n- Parses structured filenames: `YYYYMMDD_VENDOR_JPYAMOUNT_description.pdf`\n- Extracts: date, vendor, amount, description\n- Known vendor auto-categorization (Amazon→消耗品費, JR→旅費交通費, etc.)\n- Confidence: 0.75\n\n**2. AI OCR Analysis (Primary)**\n- Downloads file from Supabase storage\n- Calls configured AI provider (OpenAI GPT-4V / Gemini / Claude)\n- Uses Japanese expense-specific prompts for accuracy\n- Extracts: vendor, amount, date, description, tax_amount, category\n- Confidence: 0.60-0.95 based on extraction quality\n\n**3. Additional Processing**\n- Category suggestion via 300+ vendor/keyword rules\n- Business relevance check against company 定款\n- Anomaly detection (high amounts, duplicates, suspicious timing)\n\n**v5.2 Enhancement - Company Context:**\n- Optional `context` parameter allows frontend to provide company information\n- If provided, overrides database company info for more accurate AI analysis\n- Includes: company_name, company_type, business_objectives, representative, fiscal_year, capital\n\n**Supported File Formats:** PDF, JPEG, PNG, WebP\n      ",
        "parameters": [
          {
            "in": "path",
            "name": "session_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "basic": {
                  "summary": "Basic analysis (use database company info)",
                  "value": {}
                },
                "selective_items": {
                  "summary": "Analyze specific items only",
                  "value": {
                    "item_ids": [
                      "550e8400-e29b-41d4-a716-446655440000"
                    ]
                  }
                },
                "with_context": {
                  "summary": "Analysis with company context (v5.2)",
                  "value": {
                    "context": {
                      "business_objectives": [
                        "ソフトウェア開発",
                        "IT コンサルティング"
                      ],
                      "capital": "1,000,000円",
                      "company_name": "合同会社テスト",
                      "company_type": "合同会社",
                      "fiscal_year": "2025年4月〜2026年3月",
                      "representative": "代表社員 山田太郎"
                    }
                  }
                }
              },
              "schema": {
                "properties": {
                  "context": {
                    "description": "Company context for AI analysis (v5.2). If provided, overrides database company info.",
                    "properties": {
                      "business_objectives": {
                        "description": "事業目的（定款より）",
                        "example": [
                          "ソフトウェアの企画、開発、販売",
                          "ITコンサルティング"
                        ],
                        "items": {
                          "type": "string"
                        },
                        "type": "array"
                      },
                      "capital": {
                        "description": "資本金",
                        "example": "1,000,000円",
                        "type": "string"
                      },
                      "company_name": {
                        "description": "会社名",
                        "example": "株式会社サンプル",
                        "type": "string"
                      },
                      "company_type": {
                        "description": "会社形態",
                        "example": "株式会社",
                        "type": "string"
                      },
                      "fiscal_year": {
                        "description": "会計年度",
                        "example": "2025年4月〜2026年3月",
                        "type": "string"
                      },
                      "industry": {
                        "description": "業種",
                        "example": "IT/Software",
                        "type": "string"
                      },
                      "representative": {
                        "description": "代表者名",
                        "example": "山田太郎",
                        "type": "string"
                      }
                    },
                    "type": "object"
                  },
                  "item_ids": {
                    "description": "Specific items to analyze (optional, defaults to all pending)",
                    "items": {
                      "format": "uuid",
                      "type": "string"
                    },
                    "type": "array"
                  },
                  "skip_anomaly_detection": {
                    "default": false,
                    "type": "boolean"
                  },
                  "skip_business_relevance": {
                    "default": false,
                    "type": "boolean"
                  },
                  "skip_categorization": {
                    "default": false,
                    "type": "boolean"
                  }
                },
                "type": "object"
              }
            }
          }
        },
        "responses": {
          "202": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "estimated_time_seconds": {
                          "type": "integer"
                        },
                        "items_queued": {
                          "type": "integer"
                        },
                        "job_id": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "status": {
                          "example": "processing",
                          "type": "string"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Analysis started"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Trigger AI analysis",
        "tags": [
          "Expense Wizard"
        ]
      }
    },
    "/api/expense-wizard/sessions/{session_id}/create": {
      "post": {
        "description": "\nCreate all documents with relationships (atomic operation).\n\n**Requires:** `Idempotency-Key` header or `idempotency_key` in body\n\n**Document Chain:** Travel Report → Expense Claims → Salary Slip → Payment Statement\n\n**Bank Transaction:** Optionally creates and links a bank transaction for the payment.\n\n**v5.3 - Auto Journal Entry Creation:**\n- Set `auto_create_journal: true` to automatically create journal entries for supported document types\n- **Supported types:** `claims` (立替経費精算書), `salary_slip` (給与明細書)\n- **Unsupported types:** `travel`, `payment` - will be skipped with reason in response\n- **For claims documents:** Proper `expenses` records are created and linked via `document_expenses`\n- This enables the journal generation to work correctly with full account mappings\n- Response includes `journal_entries` field with created/failed/skipped arrays\n      ",
        "parameters": [
          {
            "in": "path",
            "name": "session_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Idempotency key to prevent duplicate creation",
            "in": "header",
            "name": "Idempotency-Key",
            "required": false,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "basic": {
                  "summary": "Basic document creation",
                  "value": {
                    "idempotency_key": "550e8400-e29b-41d4-a716-446655440000",
                    "include_doc_types": [
                      "claims",
                      "travel"
                    ]
                  }
                },
                "full": {
                  "summary": "Full options with bank transaction",
                  "value": {
                    "auto_create_journal": true,
                    "bank_transaction_config": {
                      "create_new": true,
                      "description": "立替経費精算",
                      "transaction_date": "2026-01-31"
                    },
                    "idempotency_key": "550e8400-e29b-41d4-a716-446655440002",
                    "include_doc_types": [
                      "travel",
                      "claims",
                      "salary_slip",
                      "payment"
                    ],
                    "link_to_bank_transaction": true
                  }
                },
                "with_auto_journal": {
                  "summary": "Create documents with auto journal entries (v5.3)",
                  "value": {
                    "auto_create_journal": true,
                    "idempotency_key": "550e8400-e29b-41d4-a716-446655440001",
                    "include_doc_types": [
                      "claims",
                      "salary_slip"
                    ]
                  }
                }
              },
              "schema": {
                "properties": {
                  "auto_create_journal": {
                    "default": false,
                    "description": "Auto-create journal entries for supported document types (v5.3). When true, journal entries are created atomically for claims and salary_slip documents. TRAVEL and PAYMENT types are skipped.",
                    "type": "boolean"
                  },
                  "bank_transaction_config": {
                    "properties": {
                      "create_new": {
                        "default": true,
                        "type": "boolean"
                      },
                      "description": {
                        "type": "string"
                      },
                      "existing_transaction_id": {
                        "format": "uuid",
                        "type": "string"
                      },
                      "transaction_date": {
                        "format": "date",
                        "type": "string"
                      }
                    },
                    "type": "object"
                  },
                  "idempotency_key": {
                    "maxLength": 255,
                    "type": "string"
                  },
                  "include_doc_types": {
                    "items": {
                      "enum": [
                        "travel",
                        "claims",
                        "salary_slip",
                        "payment"
                      ],
                      "type": "string"
                    },
                    "type": "array"
                  },
                  "link_to_bank_transaction": {
                    "default": true,
                    "type": "boolean"
                  }
                },
                "required": [
                  "idempotency_key"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "examples": {
                  "with_journals": {
                    "summary": "Response with auto-created journal entries",
                    "value": {
                      "data": {
                        "bank_transaction": null,
                        "completed_at": "2026-01-31T10:00:00.000Z",
                        "created_documents": [
                          {
                            "document_name": "立替経費申請書_20260131",
                            "document_type": "claims",
                            "id": "doc-uuid-1",
                            "status": "published"
                          },
                          {
                            "document_name": "出張旅費精算書_20260131",
                            "document_type": "travel",
                            "id": "doc-uuid-2",
                            "status": "published"
                          }
                        ],
                        "journal_entries": {
                          "created": [
                            {
                              "document_id": "doc-uuid-1",
                              "journal_entry_id": "journal-uuid-1"
                            }
                          ],
                          "failed": [],
                          "skipped": [
                            {
                              "document_id": "doc-uuid-2",
                              "reason": "Document type \"travel\" does not support journal entry generation"
                            }
                          ]
                        },
                        "relationships": [],
                        "session_status": "completed"
                      },
                      "message": "Documents created successfully",
                      "success": true
                    }
                  }
                },
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "bank_transaction": {
                          "nullable": true,
                          "properties": {
                            "id": {
                              "format": "uuid",
                              "type": "string"
                            },
                            "linked_document_id": {
                              "format": "uuid",
                              "type": "string"
                            },
                            "transaction_date": {
                              "type": "integer"
                            },
                            "withdrawal_amount": {
                              "type": "number"
                            }
                          },
                          "type": "object"
                        },
                        "completed_at": {
                          "format": "date-time",
                          "type": "string"
                        },
                        "created_documents": {
                          "items": {
                            "properties": {
                              "document_name": {
                                "type": "string"
                              },
                              "document_type": {
                                "type": "string"
                              },
                              "id": {
                                "format": "uuid",
                                "type": "string"
                              },
                              "status": {
                                "type": "string"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        },
                        "journal_entries": {
                          "description": "Journal entries result (only present when auto_create_journal is true)",
                          "nullable": true,
                          "properties": {
                            "created": {
                              "description": "Successfully created journal entries",
                              "items": {
                                "properties": {
                                  "document_id": {
                                    "format": "uuid",
                                    "type": "string"
                                  },
                                  "journal_entry_id": {
                                    "format": "uuid",
                                    "type": "string"
                                  }
                                },
                                "type": "object"
                              },
                              "type": "array"
                            },
                            "failed": {
                              "description": "Failed journal entry creations",
                              "items": {
                                "properties": {
                                  "document_id": {
                                    "format": "uuid",
                                    "type": "string"
                                  },
                                  "error": {
                                    "type": "string"
                                  }
                                },
                                "type": "object"
                              },
                              "type": "array"
                            },
                            "skipped": {
                              "description": "Skipped documents (unsupported types like TRAVEL, PAYMENT)",
                              "items": {
                                "properties": {
                                  "document_id": {
                                    "format": "uuid",
                                    "type": "string"
                                  },
                                  "reason": {
                                    "type": "string"
                                  }
                                },
                                "type": "object"
                              },
                              "type": "array"
                            }
                          },
                          "type": "object"
                        },
                        "relationships": {
                          "items": {
                            "properties": {
                              "child_id": {
                                "format": "uuid",
                                "type": "string"
                              },
                              "parent_id": {
                                "format": "uuid",
                                "type": "string"
                              },
                              "relationship_type": {
                                "type": "string"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        },
                        "session_status": {
                          "type": "string"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Documents created successfully"
          },
          "409": {
            "description": "Duplicate request or session already completed"
          },
          "422": {
            "description": "Unresolved critical anomalies; or a live receipt is unanalysed (pending / analyzing / failed / no amount / no date — details.unanalysed_items, BL-665); or a 出張精算 of 日当 alone has no destination or purpose (details.trip_not_named)"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create documents",
        "tags": [
          "Expense Wizard"
        ]
      }
    },
    "/api/expense-wizard/sessions/{session_id}/fare-lines": {
      "post": {
        "description": "\nBook a train fare read off a route search (e.g. Yahoo!路線情報's IC fare) as its\nown line. Under ¥30,000 a public-transport ride needs only the book entry\n(消令49①一イ, NTA インボイスQ&A 問105): the line carries the section and the\n特例 in its remarks, and no analysis runs on it. A round trip books one line per\nride, because the ¥30,000 test is per ride.\n      ",
        "parameters": [
          {
            "in": "path",
            "name": "session_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/WizardFareLinesRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "items": {
                        "$ref": "#/components/schemas/WizardItem"
                      },
                      "type": "array"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "The fare lines booked (two for a round trip)"
          },
          "400": {
            "description": "Invalid body, a fare of ¥30,000 or more, or a finished session"
          },
          "404": {
            "description": "Session not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Add a train fare with no receipt file",
        "tags": [
          "Expense Wizard"
        ]
      }
    },
    "/api/expense-wizard/sessions/{session_id}/preflight": {
      "get": {
        "description": "Read-only check the confirmation step runs before create: the claim total (the same computation preview and create use), documents of the same total, real bank transfers of the same amount, advisory warnings (entry guards, 出張規程, trip period) and the pre-create trip checklist. Nothing here blocks create except warnings with severity `error`. 日当 warnings: ALLOWANCE_WITHOUT_RULES_DOC, ALLOWANCE_RULES_CATEGORY_UNREADABLE, ALLOWANCE_RATE_NOT_FROM_RULES (the rate is a fallback or a typed override), ALLOWANCE_OVERNIGHT_WITHOUT_LODGING (宿泊 rate, no lodging, one receipt date), ALLOWANCE_DAYS_EXCEED_RECEIPT_SPAN (more 日当 days than the receipts span). Books advisories (ADR-0015) arrive in `advisories` as ADR-0014 `Advisory` cases on each receipt (target kind `expense`, grouped per session) — asset-in-service-date, capital-vs-repair, construction-in-progress; they never block.",
        "parameters": [
          {
            "in": "path",
            "name": "session_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "advisories": {
                          "description": "Books advisories for the receipts (ADR-0015); never block create",
                          "items": {
                            "$ref": "#/components/schemas/Advisory"
                          },
                          "type": "array"
                        },
                        "checklist": {
                          "$ref": "#/components/schemas/WizardTripChecklist"
                        },
                        "claimSubject": {
                          "description": "The subject every stored document name will carry: trip_info.claim_title, else destination_purpose, else places and expense kinds, else vendors. Never plain 精算.",
                          "example": "出張先A・B_交通費・宿泊",
                          "type": "string"
                        },
                        "duplicateChains": {
                          "items": {
                            "type": "object"
                          },
                          "type": "array"
                        },
                        "existingBankTransfers": {
                          "items": {
                            "type": "object"
                          },
                          "type": "array"
                        },
                        "grandTotal": {
                          "type": "number"
                        },
                        "warnings": {
                          "items": {
                            "type": "object"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Preflight result"
          },
          "404": {
            "description": "Session not found or access denied"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create-time preflight",
        "tags": [
          "Expense Wizard"
        ]
      }
    },
    "/api/expense-wizard/sessions/{session_id}/preview": {
      "post": {
        "description": "Generate document previews before creation.",
        "parameters": [
          {
            "in": "path",
            "name": "session_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "include_doc_types": {
                    "items": {
                      "enum": [
                        "travel",
                        "claims",
                        "salary_slip",
                        "payment"
                      ],
                      "type": "string"
                    },
                    "type": "array"
                  }
                },
                "type": "object"
              }
            }
          }
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "previews": {
                          "type": "object"
                        },
                        "totals": {
                          "properties": {
                            "daily_allowance": {
                              "type": "number"
                            },
                            "expense_total": {
                              "type": "number"
                            },
                            "grand_total": {
                              "type": "number"
                            },
                            "item_count": {
                              "type": "integer"
                            }
                          },
                          "type": "object"
                        },
                        "warnings": {
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Previews generated"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Preview documents",
        "tags": [
          "Expense Wizard"
        ]
      }
    },
    "/api/expense-wizard/sessions/{session_id}/reread": {
      "post": {
        "description": "\nRead completed receipts again (one card's 再読み取り, or the bulk 要確認・外貨 action).\nThe current reading stays on each item; the new one waits in the item's `reread` block\n(analysis-status and the session GET) until the owner applies or drops it. Fields the\nowner edited are kept on apply unless `overwrite_edited` is set. One request is one\nunit of the AI rate limit; the monthly AI budget and spend-cap guards apply.\n      ",
        "parameters": [
          {
            "in": "path",
            "name": "session_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "item_ids": {
                    "items": {
                      "format": "uuid",
                      "type": "string"
                    },
                    "maxItems": 50,
                    "minItems": 1,
                    "type": "array"
                  }
                },
                "required": [
                  "item_ids"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "202": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "estimated_time_seconds": {
                          "type": "integer"
                        },
                        "items_queued": {
                          "type": "integer"
                        },
                        "job_id": {
                          "format": "uuid",
                          "type": "string"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Re-read queued"
          },
          "404": {
            "description": "Session or item not found"
          },
          "409": {
            "description": "A finished session, or an item that is not read yet / already being re-read"
          },
          "429": {
            "description": "AI rate limit, monthly AI budget or spend cap reached"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Re-read receipts as a proposal",
        "tags": [
          "Expense Wizard"
        ]
      }
    },
    "/api/expense-wizard/sessions/{session_id}/stream": {
      "get": {
        "description": "\nEstablishes a Server-Sent Events (SSE) connection for real-time progress updates during expense wizard operations.\n\n**Authentication:**\nEventSource cannot send an Authorization header. Open it with `withCredentials: true`\nso the HttpOnly `access_token` cookie authenticates the stream. A token in the URL\n(`?access_token=` / `?token=`) is ignored: it would land in browser history and proxy logs.\n\n**Use Cases:**\n- Real-time AI analysis progress (instead of polling)\n- Document creation status updates\n- Cross-device session synchronization\n\n**SSE Events Emitted:**\n| Event | Description |\n|-------|-------------|\n| `wizard.connected` | Connection established |\n| `wizard.session_updated` | Session state changed |\n| `wizard.item_uploaded` | New item uploaded |\n| `wizard.analysis_started` | AI analysis began |\n| `wizard.analysis_progress` | Per-item analysis progress |\n| `wizard.analysis_completed` | All items analyzed |\n| `wizard.analysis_failed` | Analysis error |\n| `wizard.document_creating` | Document creation started |\n| `wizard.document_created` | Document created |\n| `wizard.completed` | Wizard flow completed |\n| `wizard.error` | Error occurred |\n\n**Frontend Usage:**\n```typescript\n// The HttpOnly access cookie authenticates the stream\nconst eventSource = new EventSource(`/api/expense-wizard/sessions/${sessionId}/stream`, {\n  withCredentials: true\n});\n\neventSource.addEventListener('wizard.analysis_progress', (e) => {\n  const data = JSON.parse(e.data);\n  updateProgressBar(data.percent_complete);\n  setCurrentFile(data.current_item?.file_name);\n});\n\neventSource.addEventListener('wizard.completed', (e) => {\n  const data = JSON.parse(e.data);\n  navigateToDocuments(data.created_documents);\n});\n\neventSource.onerror = () => {\n  if (eventSource.readyState === EventSource.CLOSED) {\n    // Refresh the session (rotates the cookie), then reconnect\n    reconnect();\n  }\n};\n```\n\n**Reconnection Support:**\n- Last-Event-ID header supported for message recovery\n- Server sends retry hints for automatic reconnection\n- Heartbeat every 15 seconds to detect connection loss\n      ",
        "operationId": "streamExpenseWizardSession",
        "parameters": [
          {
            "description": "Wizard session ID",
            "in": "path",
            "name": "session_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "text/event-stream": {
                "schema": {
                  "description": "Server-Sent Events stream",
                  "example": "event: wizard.analysis_progress\ndata: {\"session_id\":\"...\",\"total_items\":5,\"analyzed_items\":2,\"percent_complete\":40}\n\nevent: wizard.completed\ndata: {\"session_id\":\"...\",\"created_documents\":[{\"id\":\"...\",\"type\":\"travel\",\"name\":\"出張報告書\"}]}",
                  "type": "string"
                }
              }
            },
            "description": "SSE stream established"
          },
          "401": {
            "description": "Unauthorized - authentication required"
          },
          "404": {
            "description": "Session not found or access denied"
          },
          "429": {
            "description": "Too many connections from this IP"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "SSE stream for real-time progress updates",
        "tags": [
          "Expense Wizard"
        ]
      }
    },
    "/api/expense-wizard/sessions/{session_id}/upload": {
      "post": {
        "description": "\nUpload receipt files for AI analysis.\n\n**Supported formats:** PDF, JPEG, PNG, WebP\n**Limits:** Max 20 files per request, 10MB per file, 50 items per session\n      ",
        "parameters": [
          {
            "in": "path",
            "name": "session_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "multipart/form-data": {
              "schema": {
                "properties": {
                  "files": {
                    "description": "Receipt files to upload",
                    "items": {
                      "format": "binary",
                      "type": "string"
                    },
                    "type": "array"
                  }
                },
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "total_uploaded": {
                          "type": "integer"
                        },
                        "uploaded_items": {
                          "items": {
                            "$ref": "#/components/schemas/WizardItem"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Files uploaded successfully"
          },
          "400": {
            "description": "Invalid file type or size"
          },
          "422": {
            "description": "Maximum items per session exceeded"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Upload files to session",
        "tags": [
          "Expense Wizard"
        ]
      }
    },
    "/api/expense-wizard/sse-stats": {
      "get": {
        "description": "Returns statistics about SSE connections for monitoring purposes.",
        "operationId": "getExpenseWizardSSEStats",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "activeProgressSessions": {
                          "description": "Sessions with active progress tracking",
                          "type": "integer"
                        },
                        "averageConnectionDuration": {
                          "description": "Average connection duration in ms",
                          "type": "number"
                        },
                        "channels": {
                          "description": "Active channels",
                          "type": "integer"
                        },
                        "messagesInHistory": {
                          "description": "Messages in recovery buffer",
                          "type": "integer"
                        },
                        "totalConnections": {
                          "description": "Total active SSE connections",
                          "type": "integer"
                        },
                        "totalMessagesSent": {
                          "description": "Total messages sent",
                          "type": "integer"
                        },
                        "totalSubscriptions": {
                          "description": "Total channel subscriptions",
                          "type": "integer"
                        },
                        "uniqueUsers": {
                          "description": "Unique users connected",
                          "type": "integer"
                        },
                        "uptime": {
                          "description": "Server uptime in seconds",
                          "type": "number"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "SSE statistics"
          }
        },
        "summary": "Get SSE connection statistics",
        "tags": [
          "Expense Wizard"
        ]
      }
    },
    "/api/expense-wizard/validate-relevance": {
      "post": {
        "description": "Check if expense is relevant to company 業務内容.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "amount": {
                    "example": 89800,
                    "type": "number"
                  },
                  "category": {
                    "example": 9,
                    "type": "integer"
                  },
                  "description": {
                    "example": "掃除機",
                    "type": "string"
                  },
                  "vendor": {
                    "example": "Amazon",
                    "type": "string"
                  }
                },
                "required": [
                  "description",
                  "category",
                  "amount"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "company_objectives": {
                          "items": {
                            "type": "string"
                          },
                          "type": "array"
                        },
                        "is_relevant": {
                          "type": "boolean"
                        },
                        "matched_objective": {
                          "nullable": true,
                          "type": "string"
                        },
                        "reasoning": {
                          "type": "string"
                        },
                        "relevance_score": {
                          "type": "number"
                        },
                        "suggestions": {
                          "type": "array"
                        },
                        "warning": {
                          "nullable": true,
                          "type": "string"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Validation completed"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Validate business relevance",
        "tags": [
          "Expense Wizard"
        ]
      }
    },
    "/api/family-hiring/analyze": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ClassifyIntakeRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AnalyzeResponse"
                }
              }
            },
            "description": "分析結果 (分類・壁・最適化シナリオ)"
          }
        },
        "summary": "親族雇用 — 無状態分析 (分類・壁評価・最適化)",
        "tags": [
          "FamilyHiring"
        ]
      }
    },
    "/api/family-hiring/designs": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "description": "作成した雇用設計と分析結果"
          }
        },
        "summary": "雇用設計を作成（分類・壁評価・最適化を自動実行）",
        "tags": [
          "FamilyHiring"
        ]
      }
    },
    "/api/family-hiring/establishments": {
      "get": {
        "responses": {
          "200": {
            "description": "事業所一覧"
          }
        },
        "summary": "事業所一覧を取得",
        "tags": [
          "FamilyHiring"
        ]
      },
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "description": "作成した事業所"
          }
        },
        "summary": "事業所を新規作成",
        "tags": [
          "FamilyHiring"
        ]
      }
    },
    "/api/family-hiring/establishments/{establishment_id}": {
      "delete": {
        "parameters": [
          {
            "in": "path",
            "name": "establishment_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "204": {
            "description": "削除完了"
          }
        },
        "summary": "事業所を削除",
        "tags": [
          "FamilyHiring"
        ]
      },
      "get": {
        "parameters": [
          {
            "in": "path",
            "name": "establishment_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "事業所詳細"
          },
          "404": {
            "description": "事業所が見つかりません"
          }
        },
        "summary": "事業所詳細を取得",
        "tags": [
          "FamilyHiring"
        ]
      },
      "put": {
        "parameters": [
          {
            "in": "path",
            "name": "establishment_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "更新した事業所"
          }
        },
        "summary": "事業所を更新",
        "tags": [
          "FamilyHiring"
        ]
      }
    },
    "/api/family-hiring/hires": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "description": "追加した親族雇用"
          }
        },
        "summary": "親族雇用を新規追加",
        "tags": [
          "FamilyHiring"
        ]
      }
    },
    "/api/family-hiring/hires/{hire_id}": {
      "delete": {
        "parameters": [
          {
            "in": "path",
            "name": "hire_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "204": {
            "description": "削除完了"
          }
        },
        "summary": "親族雇用を削除",
        "tags": [
          "FamilyHiring"
        ]
      },
      "get": {
        "parameters": [
          {
            "in": "path",
            "name": "hire_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "親族雇用の詳細"
          },
          "404": {
            "description": "見つかりません"
          }
        },
        "summary": "親族雇用の詳細を取得",
        "tags": [
          "FamilyHiring"
        ]
      },
      "put": {
        "parameters": [
          {
            "in": "path",
            "name": "hire_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "更新した親族雇用"
          }
        },
        "summary": "親族雇用を更新",
        "tags": [
          "FamilyHiring"
        ]
      }
    },
    "/api/family-hiring/optimize": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "最適化結果（シナリオA–E + スウィープ）"
          }
        },
        "summary": "給与シナリオ最適化を実行",
        "tags": [
          "FamilyHiring"
        ]
      }
    },
    "/api/family-hiring/wall-monitor": {
      "get": {
        "parameters": [
          {
            "in": "query",
            "name": "hire_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "year",
            "required": true,
            "schema": {
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "壁モニタースナップショット"
          }
        },
        "summary": "壁モニタースナップショットを取得",
        "tags": [
          "FamilyHiring"
        ]
      }
    },
    "/api/family-hiring/work-logs": {
      "get": {
        "parameters": [
          {
            "in": "query",
            "name": "hire_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "year",
            "schema": {
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "month",
            "schema": {
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "勤務記録一覧"
          }
        },
        "summary": "勤務記録を取得",
        "tags": [
          "FamilyHiring"
        ]
      },
      "post": {
        "responses": {
          "201": {
            "description": "追加した勤務記録"
          }
        },
        "summary": "勤務記録を追加",
        "tags": [
          "FamilyHiring"
        ]
      }
    },
    "/api/filed-returns": {
      "get": {
        "parameters": [
          {
            "in": "query",
            "name": "fiscal_year",
            "schema": {
              "type": "integer"
            }
          },
          {
            "description": "full (default): 申告時 / 現在 / 差額 per return (recomputes the ledger and consumption tax). periods: only the filed periods (FiledReturnPeriod) — one indexed query, for banners. figures: each pin’s transmitted key boxes (FiledReturnFigures) — one query, for 年度比較.",
            "in": "query",
            "name": "view",
            "schema": {
              "default": "full",
              "enum": [
                "full",
                "periods",
                "figures"
              ],
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "oneOf": [
                    {
                      "$ref": "#/components/schemas/FiledReturnsListResult"
                    },
                    {
                      "$ref": "#/components/schemas/FiledReturnPeriodsListResult"
                    },
                    {
                      "$ref": "#/components/schemas/FiledReturnFiguresListResult"
                    }
                  ]
                }
              }
            },
            "description": "一覧 (FiledReturnsListResult; FiledReturnPeriodsListResult when view=periods; FiledReturnFiguresListResult when view=figures)"
          },
          "401": {
            "description": "未認証"
          }
        },
        "summary": "固定済み申告一覧（申告時 / 現在 / 差額）",
        "tags": [
          "FiledReturns"
        ]
      }
    },
    "/api/filed-returns/backfill": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "dry_run": {
                    "type": "boolean"
                  },
                  "fiscal_year": {
                    "type": "integer"
                  }
                },
                "type": "object"
              }
            }
          },
          "required": false
        },
        "responses": {
          "200": {
            "description": "セッションごとの結果"
          },
          "401": {
            "description": "未認証"
          }
        },
        "summary": "既に申告済みの全期間を監査ログから復元して固定する",
        "tags": [
          "FiledReturns"
        ]
      }
    },
    "/api/filed-returns/bank-reconciliation": {
      "get": {
        "parameters": [
          {
            "in": "query",
            "name": "fiscal_year",
            "required": true,
            "schema": {
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BankReconciliationReport"
                }
              }
            },
            "description": "突合結果"
          },
          "400": {
            "description": "fiscal_year 必須"
          },
          "401": {
            "description": "未認証"
          }
        },
        "summary": "銀行明細と仕訳の突合（一致 / 仕訳なし / 入出金なし）",
        "tags": [
          "FiledReturns"
        ]
      }
    },
    "/api/filed-returns/drift-findings/{finding_id}": {
      "patch": {
        "parameters": [
          {
            "in": "path",
            "name": "finding_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "explanation": {
                    "nullable": true,
                    "type": "string"
                  },
                  "status": {
                    "enum": [
                      "pending",
                      "amend_return",
                      "fix_books",
                      "explained"
                    ],
                    "type": "string"
                  }
                },
                "required": [
                  "status"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DriftFindingResult"
                }
              }
            },
            "description": "更新後の差異"
          },
          "400": {
            "description": "入力不正"
          },
          "401": {
            "description": "未認証"
          },
          "404": {
            "description": "差異なし"
          }
        },
        "summary": "差異の判断を記録する",
        "tags": [
          "FiledReturns"
        ]
      }
    },
    "/api/filed-returns/pin": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "session_id": {
                    "format": "uuid",
                    "type": "string"
                  },
                  "transmitted_at": {
                    "description": "送信日時（受付番号に時刻がない eLTAX の R1-… 番号のとき、受信通知の受付日時を渡す）。省略時は e-Tax 受付番号 → submitted_at の順",
                    "format": "date-time",
                    "type": "string"
                  }
                },
                "required": [
                  "session_id"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FiledReturnPinResult"
                }
              }
            },
            "description": "固定完了"
          },
          "400": {
            "description": "入力不正"
          },
          "401": {
            "description": "未認証"
          },
          "404": {
            "description": "セッションなし"
          },
          "409": {
            "description": "未申告、または固定済み"
          }
        },
        "summary": "申告済みセッションを固定する（受信データ + 帳簿スナップショット）",
        "tags": [
          "FiledReturns"
        ]
      }
    },
    "/api/filed-returns/{id}/drift": {
      "get": {
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "include_resolved",
            "schema": {
              "enum": [
                "true",
                "false"
              ],
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DriftFindingsResult"
                }
              }
            },
            "description": "差異一覧"
          },
          "401": {
            "description": "未認証"
          },
          "404": {
            "description": "固定済み申告なし"
          }
        },
        "summary": "差異一覧（仕訳単位・科目単位）",
        "tags": [
          "FiledReturns"
        ]
      }
    },
    "/api/filed-returns/{id}/drift/export": {
      "get": {
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "text/csv": {
                "schema": {
                  "type": "string"
                }
              }
            },
            "description": "CSV"
          },
          "401": {
            "description": "未認証"
          },
          "404": {
            "description": "固定済み申告なし"
          }
        },
        "summary": "税理士向け照合表（CSV, UTF-8 BOM）",
        "tags": [
          "FiledReturns"
        ]
      }
    },
    "/api/filed-returns/{id}/next-period-correction": {
      "get": {
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/NextPeriodCorrectionContext"
                }
              }
            },
            "description": "翌期の情報"
          },
          "401": {
            "description": "未認証"
          },
          "404": {
            "description": "固定済み申告なし"
          }
        },
        "summary": "翌期期首修正の登録先（翌期・最初に登録できる日・登録済みの修正）",
        "tags": [
          "FiledReturns"
        ]
      },
      "post": {
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "counterpart_account_code": {
                    "description": "default 302 繰越利益剰余金; null = the lines must balance",
                    "nullable": true,
                    "type": "string"
                  },
                  "description": {
                    "nullable": true,
                    "type": "string"
                  },
                  "dry_run": {
                    "type": "boolean"
                  },
                  "entry_date": {
                    "description": "YYYYMMDD inside the next period; default the 期首 (first day of the next period)",
                    "type": "integer"
                  },
                  "lines": {
                    "items": {
                      "properties": {
                        "account_code": {
                          "type": "string"
                        },
                        "credit": {
                          "minimum": 0,
                          "type": "integer"
                        },
                        "debit": {
                          "minimum": 0,
                          "type": "integer"
                        },
                        "description": {
                          "nullable": true,
                          "type": "string"
                        },
                        "drift_finding_id": {
                          "format": "uuid",
                          "nullable": true,
                          "type": "string"
                        },
                        "note": {
                          "description": "e.g. 税理士確認事項 No.7",
                          "nullable": true,
                          "type": "string"
                        },
                        "tax_code": {
                          "description": "税区分 (default 4 不課税). On a date in a filed 消費税 quarter only 4 / 5 are accepted (423 otherwise)",
                          "maximum": 5,
                          "minimum": 1,
                          "type": "integer"
                        }
                      },
                      "required": [
                        "account_code"
                      ],
                      "type": "object"
                    },
                    "minItems": 1,
                    "type": "array"
                  }
                },
                "required": [
                  "lines"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/NextPeriodCorrectionResult"
                }
              }
            },
            "description": "Dry run"
          },
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/NextPeriodCorrectionResult"
                }
              }
            },
            "description": "登録した仕訳"
          },
          "400": {
            "description": "入力不正（貸借不一致・科目なし）"
          },
          "401": {
            "description": "未認証"
          },
          "404": {
            "description": "固定済み申告なし"
          },
          "422": {
            "description": "翌期の外の日付 / 翌期に登録できる日がない"
          },
          "423": {
            "description": "この期間は申告済みです / 申告済みの消費税の課税期間に消費税の区分が付いた明細"
          }
        },
        "summary": "翌期期首修正を登録する（前期損益修正・相手科目は既定で繰越利益剰余金）",
        "tags": [
          "FiledReturns"
        ]
      }
    },
    "/api/filed-returns/{id}/recompute": {
      "post": {
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "再計算結果"
          },
          "401": {
            "description": "未認証"
          },
          "404": {
            "description": "固定済み申告なし"
          }
        },
        "summary": "差異を再計算する",
        "tags": [
          "FiledReturns"
        ]
      }
    },
    "/api/filed-returns/{id}/restore": {
      "post": {
        "description": "BE ADR-0029. dry_run (default) lists the entries to void / return to their as-filed state / restore line amounts, the per-account effect and a confirmation token. dry_run=false with that token applies it in one transaction and verifies the period’s balances equal the pin, else rolls back. 税額・お金は変わりません。",
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "confirmation_token": {
                    "pattern": "^[0-9a-f]{64}$",
                    "type": "string"
                  },
                  "dry_run": {
                    "default": true,
                    "type": "boolean"
                  }
                },
                "type": "object"
              }
            }
          }
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "oneOf": [
                    {
                      "$ref": "#/components/schemas/FiledReturnRestorePreview"
                    },
                    {
                      "$ref": "#/components/schemas/FiledReturnRestoreResult"
                    }
                  ]
                }
              }
            },
            "description": "Preview (dry run) or the applied result"
          },
          "400": {
            "description": "入力不正（適用には確認トークンが必要）"
          },
          "401": {
            "description": "未認証"
          },
          "404": {
            "description": "固定済み申告なし"
          },
          "409": {
            "description": "プレビュー後に帳簿が変わった / 検証で不一致（ロールバック済み）"
          },
          "422": {
            "description": "戻せない変更がある（blockers）"
          }
        },
        "summary": "申告時点に戻す（プレビュー → 確認トークンで適用）",
        "tags": [
          "FiledReturns"
        ]
      }
    },
    "/api/insights": {
      "get": {
        "description": "Get all active insights for the user",
        "operationId": "getAllInsights",
        "parameters": [
          {
            "description": "Filter by status",
            "in": "query",
            "name": "status",
            "required": false,
            "schema": {
              "enum": [
                "new",
                "viewed",
                "acted",
                "dismissed"
              ],
              "type": "string"
            }
          },
          {
            "description": "Filter by type",
            "in": "query",
            "name": "type",
            "required": false,
            "schema": {
              "enum": [
                "tax_saving",
                "compliance_warning",
                "deadline",
                "optimization",
                "missing_document"
              ],
              "type": "string"
            }
          },
          {
            "description": "Maximum insights to return",
            "in": "query",
            "name": "limit",
            "required": false,
            "schema": {
              "default": 50,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "insights": {
                          "items": {
                            "$ref": "#/components/schemas/ProactiveInsight"
                          },
                          "type": "array"
                        },
                        "total": {
                          "type": "integer"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Insights retrieved"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get all insights",
        "tags": [
          "Insights"
        ]
      }
    },
    "/api/insights/contextual": {
      "get": {
        "description": "Get insights relevant to the current screen context",
        "operationId": "getContextualInsights",
        "parameters": [
          {
            "description": "Current screen identifier",
            "example": "expense_wizard",
            "in": "query",
            "name": "screen",
            "required": true,
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "Optional document type for context",
            "in": "query",
            "name": "document_type",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "Maximum insights to return",
            "in": "query",
            "name": "limit",
            "required": false,
            "schema": {
              "default": 5,
              "maximum": 20,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/ContextualInsightsResponse"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Contextual insights retrieved"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get contextual insights",
        "tags": [
          "Insights"
        ]
      }
    },
    "/api/insights/count": {
      "get": {
        "description": "Get insight counts by priority",
        "operationId": "getInsightCounts",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/InsightCountsResponse"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Insight counts retrieved"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get insight counts",
        "tags": [
          "Insights"
        ]
      }
    },
    "/api/insights/generate": {
      "post": {
        "description": "Manually trigger insight generation",
        "operationId": "generateInsights",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "force_regenerate": {
                    "default": false,
                    "description": "Whether to regenerate existing insights",
                    "type": "boolean"
                  }
                },
                "type": "object"
              }
            }
          }
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "generated": {
                          "example": 3,
                          "type": "integer"
                        },
                        "types": {
                          "example": [
                            "tax_saving",
                            "deadline",
                            "compliance_warning"
                          ],
                          "items": {
                            "type": "string"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Generated 3 insights",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Insights generated"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Generate insights",
        "tags": [
          "Insights"
        ]
      }
    },
    "/api/insights/{insight_id}/dismiss": {
      "post": {
        "description": "Dismiss an insight (will resurface after 30 days)",
        "operationId": "dismissInsight",
        "parameters": [
          {
            "description": "Insight ID",
            "in": "path",
            "name": "insight_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "reason": {
                    "description": "Optional reason for dismissal",
                    "type": "string"
                  }
                },
                "type": "object"
              }
            }
          }
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "message": {
                      "example": "Insight dismissed",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Insight dismissed"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Dismiss insight",
        "tags": [
          "Insights"
        ]
      }
    },
    "/api/insights/{insight_id}/view": {
      "post": {
        "description": "Mark an insight as viewed by the user",
        "operationId": "markInsightViewed",
        "parameters": [
          {
            "description": "Insight ID",
            "in": "path",
            "name": "insight_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "message": {
                      "example": "Insight marked as viewed",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Insight marked as viewed"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Mark insight as viewed",
        "tags": [
          "Insights"
        ]
      }
    },
    "/api/journal-templates": {
      "get": {
        "description": "Returns all templates for the authenticated user, sorted by shortcut key, usage, and name",
        "parameters": [
          {
            "description": "Include inactive templates (default false)",
            "in": "query",
            "name": "include_inactive",
            "schema": {
              "type": "boolean"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "items": {
                        "$ref": "#/components/schemas/JournalTemplate"
                      },
                      "type": "array"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "List of journal templates"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List journal templates (仕訳辞書一覧)",
        "tags": [
          "Journal Templates"
        ]
      },
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "credit_account_id": {
                    "format": "uuid",
                    "type": "string"
                  },
                  "debit_account_id": {
                    "format": "uuid",
                    "type": "string"
                  },
                  "default_amount": {
                    "description": "Default amount (optional)",
                    "type": "number"
                  },
                  "default_description": {
                    "description": "Default journal entry description",
                    "type": "string"
                  },
                  "description": {
                    "description": "Template description",
                    "type": "string"
                  },
                  "name": {
                    "description": "Template name (e.g., \"交通費精算\")",
                    "maxLength": 100,
                    "type": "string"
                  },
                  "shortcut_key": {
                    "description": "Shortcut key (F1-F5)",
                    "maxLength": 10,
                    "type": "string"
                  },
                  "tax_included": {
                    "default": false,
                    "type": "boolean"
                  },
                  "tax_rate": {
                    "default": "standard_10",
                    "enum": [
                      "standard_10",
                      "reduced_8",
                      "non_taxable",
                      "tax_exempt",
                      "outside_scope"
                    ],
                    "type": "string"
                  }
                },
                "required": [
                  "name",
                  "debit_account_id",
                  "credit_account_id"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "description": "Template created"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create journal template (仕訳辞書作成)",
        "tags": [
          "Journal Templates"
        ]
      }
    },
    "/api/journal-templates/{id}": {
      "delete": {
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Template deleted"
          },
          "404": {
            "description": "Template not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Delete journal template (soft delete)",
        "tags": [
          "Journal Templates"
        ]
      },
      "get": {
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Template details"
          },
          "404": {
            "description": "Template not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get journal template by ID",
        "tags": [
          "Journal Templates"
        ]
      },
      "put": {
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "credit_account_id": {
                    "format": "uuid",
                    "type": "string"
                  },
                  "debit_account_id": {
                    "format": "uuid",
                    "type": "string"
                  },
                  "default_amount": {
                    "type": "number"
                  },
                  "default_description": {
                    "type": "string"
                  },
                  "description": {
                    "type": "string"
                  },
                  "is_active": {
                    "type": "boolean"
                  },
                  "name": {
                    "type": "string"
                  },
                  "shortcut_key": {
                    "type": "string"
                  },
                  "tax_included": {
                    "type": "boolean"
                  },
                  "tax_rate": {
                    "type": "string"
                  }
                },
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Template updated"
          },
          "404": {
            "description": "Template not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update journal template",
        "tags": [
          "Journal Templates"
        ]
      }
    },
    "/api/journal-templates/{id}/apply": {
      "post": {
        "description": "Creates a new journal entry using the template's account settings",
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "amount": {
                    "description": "Transaction amount (overrides template default)",
                    "example": 5000,
                    "type": "number"
                  },
                  "description": {
                    "description": "Optional description (overrides template default)",
                    "type": "string"
                  },
                  "entry_date": {
                    "description": "Entry date in YYYYMMDD format",
                    "example": 20251205,
                    "type": "integer"
                  }
                },
                "required": [
                  "entry_date",
                  "amount"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "description": "Journal entry created from template"
          },
          "404": {
            "description": "Template not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Apply template to create journal entry (仕訳辞書適用)",
        "tags": [
          "Journal Templates"
        ]
      }
    },
    "/api/knowledge/articles/{article_id}": {
      "get": {
        "description": "Get full article content by ID",
        "operationId": "getKnowledgeArticle",
        "parameters": [
          {
            "description": "Article identifier",
            "example": "kb_expense_consumables",
            "in": "path",
            "name": "article_id",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "article": {
                          "$ref": "#/components/schemas/KnowledgeArticle"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Article content"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Article not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get article by ID",
        "tags": [
          "Knowledge Base"
        ]
      }
    },
    "/api/knowledge/categories": {
      "get": {
        "description": "Get list of all categories with article counts",
        "operationId": "getKnowledgeCategories",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "categories": {
                          "items": {
                            "$ref": "#/components/schemas/KnowledgeCategory"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Categories list"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get all categories",
        "tags": [
          "Knowledge Base"
        ]
      }
    },
    "/api/knowledge/categories/{category}": {
      "get": {
        "description": "Get all articles in a specific category",
        "operationId": "getArticlesByCategory",
        "parameters": [
          {
            "description": "Category identifier",
            "example": "expense",
            "in": "path",
            "name": "category",
            "required": true,
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "Maximum articles",
            "in": "query",
            "name": "limit",
            "required": false,
            "schema": {
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "articles": {
                          "items": {
                            "$ref": "#/components/schemas/KnowledgeArticle"
                          },
                          "type": "array"
                        },
                        "category": {
                          "type": "string"
                        },
                        "totalArticles": {
                          "type": "integer"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Articles in category"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get articles by category",
        "tags": [
          "Knowledge Base"
        ]
      }
    },
    "/api/knowledge/learn-more": {
      "get": {
        "description": "Get detailed content for advisor UI \"詳しく\" buttons",
        "operationId": "getLearnMoreContent",
        "parameters": [
          {
            "description": "Topic to get content for",
            "example": "消耗品費",
            "in": "query",
            "name": "topic",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "articleId": {
                          "nullable": true,
                          "type": "string"
                        },
                        "content": {
                          "nullable": true,
                          "type": "string"
                        },
                        "found": {
                          "type": "boolean"
                        },
                        "legalBasis": {
                          "nullable": true,
                          "type": "array"
                        },
                        "relatedTopics": {
                          "nullable": true,
                          "type": "array"
                        },
                        "summary": {
                          "nullable": true,
                          "type": "string"
                        },
                        "title": {
                          "nullable": true,
                          "type": "string"
                        },
                        "warnings": {
                          "nullable": true,
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Learn more content"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get \"Learn More\" content",
        "tags": [
          "Knowledge Base"
        ]
      }
    },
    "/api/knowledge/screen/{screen}": {
      "get": {
        "description": "Get articles relevant to a specific UI screen",
        "operationId": "getArticlesForScreen",
        "parameters": [
          {
            "description": "Screen identifier",
            "example": "expense_wizard",
            "in": "path",
            "name": "screen",
            "required": true,
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "Maximum articles",
            "in": "query",
            "name": "limit",
            "required": false,
            "schema": {
              "default": 5,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "articles": {
                          "items": {
                            "$ref": "#/components/schemas/KnowledgeArticle"
                          },
                          "type": "array"
                        },
                        "screen": {
                          "type": "string"
                        },
                        "totalArticles": {
                          "type": "integer"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Articles for screen"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get articles for screen",
        "tags": [
          "Knowledge Base"
        ]
      }
    },
    "/api/knowledge/search": {
      "get": {
        "description": "Search articles by query string with optional filters",
        "operationId": "searchKnowledgeBase",
        "parameters": [
          {
            "description": "Search query",
            "example": "消耗品 経費",
            "in": "query",
            "name": "q",
            "required": true,
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "Filter by category",
            "in": "query",
            "name": "category",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "Filter by relevant screen",
            "in": "query",
            "name": "screen",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "Maximum results",
            "in": "query",
            "name": "limit",
            "required": false,
            "schema": {
              "default": 10,
              "type": "integer"
            }
          },
          {
            "description": "Include full content",
            "in": "query",
            "name": "include_content",
            "required": false,
            "schema": {
              "default": false,
              "type": "boolean"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "query": {
                          "type": "string"
                        },
                        "results": {
                          "items": {
                            "$ref": "#/components/schemas/SearchResult"
                          },
                          "type": "array"
                        },
                        "totalResults": {
                          "type": "integer"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Search results"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Search knowledge base",
        "tags": [
          "Knowledge Base"
        ]
      }
    },
    "/api/knowledge/tips": {
      "get": {
        "description": "Get short tips for a context (screen or category)",
        "operationId": "getKnowledgeTips",
        "parameters": [
          {
            "description": "Screen identifier",
            "in": "query",
            "name": "screen",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "Category filter",
            "in": "query",
            "name": "category",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "Maximum tips",
            "in": "query",
            "name": "limit",
            "required": false,
            "schema": {
              "default": 3,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "tips": {
                          "items": {
                            "type": "string"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Tips list"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get contextual tips",
        "tags": [
          "Knowledge Base"
        ]
      }
    },
    "/api/layout/init": {
      "get": {
        "description": "Composite endpoint for the app chrome. Sections are read in parallel (at most 4 at a time) and each one fails independently: a failed section is `null` (or its documented empty value) and never fails the call.\n\n**Default sections** (no `include`): company, accounts, reminders, gamification, insights, preferences, establishment, holidays, documentStatistics, accountingSettings, gamificationDefinitions, prefectures, bankConnections, advisorConversations.\n\n**Opt-in sections** (only when named in `include`): uiPreferences, aiSettings, fiscalPeriods, disclaimer. They change on a user action, so they are computed on every call and never served from the per-user in-process cache that the other sections share (120 s).\n\n`include` keys are case-insensitive; unknown keys are ignored. The session probe (`GET /api/auth/me/light`) is deliberately NOT a section: this endpoint requires the session that probe establishes.\n\n**Caching:** `Cache-Control: private, no-cache` with an ETag — the browser revalidates every use (304 when unchanged).",
        "operationId": "getLayoutInit",
        "parameters": [
          {
            "description": "Comma-separated section keys (case-insensitive), e.g. `company,accounts,uiPreferences,disclaimer`. Omit for the default sections.",
            "in": "query",
            "name": "include",
            "required": false,
            "schema": {
              "example": "company,accounts,reminders,uiPreferences,fiscalPeriods",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LayoutInitResponse"
                }
              }
            },
            "description": "The requested sections",
            "headers": {
              "Cache-Control": {
                "schema": {
                  "example": "private, no-cache",
                  "type": "string"
                }
              },
              "ETag": {
                "schema": {
                  "example": "W/\"3f1c9a0b7d2e4c61\"",
                  "type": "string"
                }
              }
            }
          },
          "304": {
            "description": "Not modified (If-None-Match matched the ETag)"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get the app shell data in one request",
        "tags": [
          "Layout"
        ]
      }
    },
    "/api/messages/categories": {
      "get": {
        "description": "Get list of all message categories and their methods",
        "operationId": "getMessageCategories",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "categories": {
                          "items": {
                            "$ref": "#/components/schemas/MessageCategory"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Categories list"
          }
        },
        "summary": "Get all message categories",
        "tags": [
          "Message Library"
        ]
      }
    },
    "/api/messages/error-responses": {
      "get": {
        "description": "Get all error response templates",
        "operationId": "getErrorResponses",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "errorResponses": {
                          "items": {
                            "$ref": "#/components/schemas/ErrorResponse"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Error responses"
          }
        },
        "summary": "Get all error responses",
        "tags": [
          "Message Library"
        ]
      }
    },
    "/api/messages/helpers": {
      "get": {
        "description": "Get examples of helper methods (tone, formatting, icons)",
        "operationId": "getMessageHelpers",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "helpers": {
                          "properties": {
                            "formattingExamples": {
                              "type": "object"
                            },
                            "gradeMapping": {
                              "type": "object"
                            },
                            "statusIcons": {
                              "type": "object"
                            },
                            "toneExamples": {
                              "type": "object"
                            }
                          },
                          "type": "object"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Helper examples"
          }
        },
        "summary": "Get helper method examples",
        "tags": [
          "Message Library"
        ]
      }
    },
    "/api/messages/loading-states": {
      "get": {
        "description": "Get all loading state message templates",
        "operationId": "getLoadingStates",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "loadingStates": {
                          "properties": {
                            "analysis": {
                              "$ref": "#/components/schemas/LoadingState"
                            },
                            "chat": {
                              "$ref": "#/components/schemas/LoadingState"
                            }
                          },
                          "type": "object"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Loading states"
          }
        },
        "summary": "Get all loading states",
        "tags": [
          "Message Library"
        ]
      }
    },
    "/api/messages/preview": {
      "post": {
        "description": "Generate a message with custom parameters",
        "operationId": "previewMessage",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "method": {
                    "description": "Method name to call",
                    "example": "expenseAllOk",
                    "type": "string"
                  },
                  "params": {
                    "example": [
                      5,
                      62000
                    ],
                    "oneOf": [
                      {
                        "description": "Array of parameters",
                        "items": {},
                        "type": "array"
                      },
                      {
                        "description": "Named parameters",
                        "type": "object"
                      }
                    ]
                  }
                },
                "required": [
                  "method"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "method": {
                          "type": "string"
                        },
                        "params": {},
                        "result": {
                          "$ref": "#/components/schemas/AdvisorMessage"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Generated message"
          },
          "404": {
            "description": "Method not found"
          }
        },
        "summary": "Preview a message",
        "tags": [
          "Message Library"
        ]
      }
    },
    "/api/messages/{category}": {
      "get": {
        "description": "Get all messages in a category with example outputs",
        "operationId": "getMessagesByCategory",
        "parameters": [
          {
            "description": "Category identifier",
            "example": "expense",
            "in": "path",
            "name": "category",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "category": {
                          "type": "string"
                        },
                        "examples": {
                          "additionalProperties": {
                            "$ref": "#/components/schemas/AdvisorMessage"
                          },
                          "type": "object"
                        },
                        "methods": {
                          "items": {
                            "type": "string"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Messages with examples"
          },
          "404": {
            "description": "Category not found"
          }
        },
        "summary": "Get messages by category",
        "tags": [
          "Message Library"
        ]
      }
    },
    "/api/official-rules/search": {
      "get": {
        "description": "PGroonga + pgvector RRF over e-Gov statutes, NTA Tax Answer, and curated articles. eLTax rows are link-only (body not stored).",
        "parameters": [
          {
            "in": "query",
            "name": "q",
            "required": true,
            "schema": {
              "maxLength": 200,
              "minLength": 1,
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "sources",
            "required": false,
            "schema": {
              "description": "Comma-separated: egov,nta_taxanswer,nta_tsutatsu,etax,eltax_link,curated. An unrecognised token returns 400.",
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "as_of",
            "required": false,
            "schema": {
              "pattern": "^\\d{4}-\\d{2}-\\d{2}$",
              "type": "string"
            }
          },
          {
            "description": "Retrieval depth. Defaults to page × page_size (capped at 30).",
            "in": "query",
            "name": "limit",
            "required": false,
            "schema": {
              "maximum": 30,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "page",
            "required": false,
            "schema": {
              "default": 1,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "page_size",
            "required": false,
            "schema": {
              "default": 10,
              "maximum": 30,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "items": {
                          "items": {
                            "type": "object"
                          },
                          "type": "array"
                        },
                        "mode": {
                          "enum": [
                            "hybrid",
                            "lexical_only",
                            "empty"
                          ],
                          "type": "string"
                        },
                        "pagination": {
                          "properties": {
                            "currentPage": {
                              "type": "integer"
                            },
                            "hasNext": {
                              "type": "boolean"
                            },
                            "hasPrevious": {
                              "type": "boolean"
                            },
                            "pageSize": {
                              "type": "integer"
                            },
                            "totalItems": {
                              "type": "integer"
                            },
                            "totalPages": {
                              "type": "integer"
                            }
                          },
                          "required": [
                            "currentPage",
                            "pageSize",
                            "totalItems",
                            "totalPages",
                            "hasNext",
                            "hasPrevious"
                          ],
                          "type": "object"
                        },
                        "query": {
                          "type": "string"
                        }
                      },
                      "required": [
                        "items",
                        "mode",
                        "query",
                        "pagination"
                      ],
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Search hits with canonical pagination"
          },
          "400": {
            "description": "Invalid query"
          },
          "401": {
            "description": "Unauthorized"
          },
          "503": {
            "description": "Search unavailable"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Hybrid search over curated official tax/legal rules",
        "tags": [
          "Official Rules"
        ]
      }
    },
    "/api/reconciliation/bulk-link": {
      "post": {
        "description": "Link multiple documents to a single bank transaction with a shared linkage type. A link or unlink that would move the credit of the 仕訳 on this bank row in a filed or closed 課税期間 (including a quarter whose return is filed while its period row is still open) is refused with 423 PERIOD_LOCKED, unless a 修正申告 for that fiscal year is open. With create_journal_entry, a row that has no 仕訳 yet is checked on its transaction date.",
        "operationId": "bulkLink",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "bankTransactionId": {
                    "format": "uuid",
                    "type": "string"
                  },
                  "createJournalEntry": {
                    "default": true,
                    "type": "boolean"
                  },
                  "linkageType": {
                    "$ref": "#/components/schemas/LinkageType"
                  },
                  "links": {
                    "items": {
                      "properties": {
                        "amount": {
                          "type": "number"
                        },
                        "documentId": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "documentType": {
                          "$ref": "#/components/schemas/DocumentType"
                        }
                      },
                      "type": "object"
                    },
                    "type": "array"
                  }
                },
                "required": [
                  "bankTransactionId",
                  "links",
                  "linkageType"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Bulk links created successfully"
          },
          "423": {
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetails"
                }
              }
            },
            "description": "The 仕訳 on this bank row is in a filed or closed 課税期間 (PERIOD_LOCKED)"
          }
        },
        "summary": "Bulk link multiple documents",
        "tags": [
          "Reconciliation Linkage"
        ]
      }
    },
    "/api/reconciliation/link": {
      "post": {
        "description": "Create one or more links between documents and a bank transaction with optional journal entry creation. Auto-creates document from file_uploads if needed. Includes P2034 deadlock retry (v4.18). A link or unlink that would move the credit of the 仕訳 on this bank row in a filed or closed 課税期間 (including a quarter whose return is filed while its period row is still open) is refused with 423 PERIOD_LOCKED, unless a 修正申告 for that fiscal year is open. With create_journal_entry, a row that has no 仕訳 yet is checked on its transaction date.",
        "operationId": "createLink",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/LinkDocumentRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/LinkDocumentResponse"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Links created successfully"
          },
          "400": {
            "description": "Bad request - invalid parameters"
          },
          "401": {
            "description": "Unauthorized"
          },
          "423": {
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetails"
                }
              }
            },
            "description": "The 仕訳 on this bank row is in a filed or closed 課税期間 (PERIOD_LOCKED)"
          }
        },
        "summary": "Link document(s) to bank transaction",
        "tags": [
          "Reconciliation Linkage"
        ]
      }
    },
    "/api/reconciliation/link-stats": {
      "get": {
        "description": "Get link statistics for audit/compliance reporting dashboard",
        "operationId": "getLinkStatistics",
        "parameters": [
          {
            "description": "Optional company filter",
            "in": "header",
            "name": "x-company-id",
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "averageMatchScore": {
                          "type": "number"
                        },
                        "byDocumentType": {
                          "additionalProperties": {
                            "type": "integer"
                          },
                          "type": "object"
                        },
                        "byLinkageType": {
                          "additionalProperties": {
                            "type": "integer"
                          },
                          "type": "object"
                        },
                        "linkedThisMonth": {
                          "type": "integer"
                        },
                        "linkedThisWeek": {
                          "type": "integer"
                        },
                        "pendingReview": {
                          "type": "integer"
                        },
                        "recentActivity": {
                          "items": {
                            "properties": {
                              "action": {
                                "type": "string"
                              },
                              "createdAt": {
                                "type": "string"
                              },
                              "documentName": {
                                "type": "string"
                              },
                              "id": {
                                "type": "string"
                              },
                              "linkageType": {
                                "type": "string"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        },
                        "totalLinks": {
                          "type": "integer"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Statistics retrieved"
          }
        },
        "summary": "Get link statistics (Compliance)",
        "tags": [
          "Reconciliation Linkage"
        ]
      }
    },
    "/api/reconciliation/links": {
      "get": {
        "description": "Retrieve links with optional filters. Response includes enriched document info (fileName, fileSize, mimeType, thumbnailUrl) from file_uploads table.",
        "operationId": "getLinks",
        "parameters": [
          {
            "description": "Filter by bank transaction",
            "in": "query",
            "name": "bankTransactionId",
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Filter by document",
            "in": "query",
            "name": "documentId",
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Filter by linkage type",
            "in": "query",
            "name": "linkageType",
            "schema": {
              "$ref": "#/components/schemas/LinkageType"
            }
          },
          {
            "description": "Include audit trail",
            "in": "query",
            "name": "includeAuditLog",
            "schema": {
              "default": false,
              "type": "boolean"
            }
          },
          {
            "in": "query",
            "name": "limit",
            "schema": {
              "default": 50,
              "maximum": 100,
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "offset",
            "schema": {
              "default": 0,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/GetLinksResponse"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Links retrieved with enriched document details"
          }
        },
        "summary": "Get document-transaction links (v4.17: enriched)",
        "tags": [
          "Reconciliation Linkage"
        ]
      }
    },
    "/api/reconciliation/links/{id}": {
      "get": {
        "description": "Get a single link with full details and audit history",
        "operationId": "getLinkById",
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Link retrieved successfully"
          },
          "404": {
            "description": "Link not found"
          }
        },
        "summary": "Get link by ID",
        "tags": [
          "Reconciliation Linkage"
        ]
      }
    },
    "/api/reconciliation/recurring-suggestions": {
      "get": {
        "description": "Auto-detect recurring transactions and suggest auto-linking rules",
        "operationId": "getRecurringSuggestions",
        "parameters": [
          {
            "description": "Minimum occurrences to qualify as recurring",
            "in": "query",
            "name": "minOccurrences",
            "schema": {
              "default": 3,
              "maximum": 12,
              "minimum": 3,
              "type": "integer"
            }
          },
          {
            "description": "Maximum patterns to return",
            "in": "query",
            "name": "limit",
            "schema": {
              "default": 20,
              "maximum": 100,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "count": {
                          "type": "integer"
                        },
                        "patterns": {
                          "items": {
                            "properties": {
                              "averageAmount": {
                                "type": "number"
                              },
                              "frequency": {
                                "enum": [
                                  "weekly",
                                  "monthly",
                                  "quarterly",
                                  "annual"
                                ],
                                "type": "string"
                              },
                              "lastOccurrence": {
                                "type": "string"
                              },
                              "occurrenceCount": {
                                "type": "integer"
                              },
                              "sampleTransactions": {
                                "items": {
                                  "properties": {
                                    "amount": {
                                      "type": "number"
                                    },
                                    "date": {
                                      "type": "string"
                                    },
                                    "description": {
                                      "type": "string"
                                    },
                                    "id": {
                                      "type": "string"
                                    }
                                  },
                                  "type": "object"
                                },
                                "type": "array"
                              },
                              "suggestedRule": {
                                "properties": {
                                  "accountCode": {
                                    "type": "string"
                                  },
                                  "accountName": {
                                    "type": "string"
                                  },
                                  "linkageType": {
                                    "type": "string"
                                  }
                                },
                                "type": "object"
                              },
                              "vendorPattern": {
                                "type": "string"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Recurring patterns found"
          }
        },
        "summary": "Get recurring pattern suggestions",
        "tags": [
          "Reconciliation Linkage"
        ]
      }
    },
    "/api/reconciliation/unlink": {
      "post": {
        "description": "Unlink a document from a bank transaction with optional reason for audit. A link or unlink that would move the credit of the 仕訳 on this bank row in a filed or closed 課税期間 (including a quarter whose return is filed while its period row is still open) is refused with 423 PERIOD_LOCKED, unless a 修正申告 for that fiscal year is open. With create_journal_entry, a row that has no 仕訳 yet is checked on its transaction date.",
        "operationId": "unlink",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "description": "Name the link by linkId, or by bankTransactionId + documentId (resolved within the caller). Neither → 400.",
                "properties": {
                  "bankTransactionId": {
                    "format": "uuid",
                    "type": "string"
                  },
                  "documentId": {
                    "description": "Document id, or the file id of a 証憑 link",
                    "format": "uuid",
                    "type": "string"
                  },
                  "linkId": {
                    "format": "uuid",
                    "type": "string"
                  },
                  "reason": {
                    "description": "Reason for unlinking (for audit)",
                    "type": "string"
                  }
                },
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Link removed successfully"
          },
          "400": {
            "description": "No linkId and no resolvable bankTransactionId + documentId pair"
          },
          "423": {
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetails"
                }
              }
            },
            "description": "The 仕訳 on this bank row is in a filed or closed 課税期間 (PERIOD_LOCKED)"
          }
        },
        "summary": "Remove a document-transaction link",
        "tags": [
          "Reconciliation Linkage"
        ]
      }
    },
    "/api/settlement-pack/candidates": {
      "get": {
        "parameters": [
          {
            "in": "query",
            "name": "payee",
            "schema": {
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "month",
            "schema": {
              "example": 202607,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "claims": {
                      "items": {
                        "$ref": "#/components/schemas/SettlementPackCandidate"
                      },
                      "type": "array"
                    },
                    "totalAmount": {
                      "type": "integer"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Candidate claims"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "summary": "List unsettled claims eligible for 合算支払",
        "tags": [
          "Settlement Pack"
        ]
      }
    },
    "/api/settlement-pack/create": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "confirm": {
                    "type": "boolean"
                  },
                  "pay_date": {
                    "example": "2026-08-25",
                    "type": "string"
                  },
                  "source_document_ids": {
                    "items": {
                      "format": "uuid",
                      "type": "string"
                    },
                    "type": "array"
                  },
                  "transfer_guard": {
                    "$ref": "#/components/schemas/TransferGuard"
                  }
                },
                "required": [
                  "source_document_ids",
                  "confirm"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SettlementPackCreateResult"
                }
              }
            },
            "description": "Created or reused"
          },
          "400": {
            "description": "Validation error"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "A named claim is missing or not owned"
          },
          "409": {
            "description": "A claim is not booked to 役員借入金, is already paid, or partly overlaps an existing grouped payment; or integrity drift"
          }
        },
        "summary": "Create one itemized 支払明細書 and N expense_to_payment edges",
        "tags": [
          "Settlement Pack"
        ]
      }
    },
    "/api/settlement-pack/payouts": {
      "get": {
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "payeeBank": {
                      "$ref": "#/components/schemas/PayeeBank"
                    },
                    "payouts": {
                      "items": {
                        "$ref": "#/components/schemas/PayoutGroup"
                      },
                      "type": "array"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Payout groups"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "summary": "List 合算支払明細書 with each claim's paid state and the officer's 振込先",
        "tags": [
          "Settlement Pack"
        ]
      }
    },
    "/api/settlement-pack/payouts/match-candidates": {
      "get": {
        "parameters": [
          {
            "explode": true,
            "in": "query",
            "name": "payment_document_ids",
            "required": true,
            "schema": {
              "items": {
                "format": "uuid",
                "type": "string"
              },
              "type": "array"
            },
            "style": "form"
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "payouts": {
                      "items": {
                        "$ref": "#/components/schemas/PayoutGroup"
                      },
                      "type": "array"
                    },
                    "remainingAmount": {
                      "type": "integer"
                    },
                    "transfers": {
                      "items": {
                        "$ref": "#/components/schemas/PayoutTransferCandidate"
                      },
                      "type": "array"
                    },
                    "unsettledClaims": {
                      "items": {
                        "$ref": "#/components/schemas/PayoutClaim"
                      },
                      "type": "array"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Candidates"
          },
          "400": {
            "description": "Validation error"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "A named 支払明細書 is missing, not owned, or not a group"
          }
        },
        "summary": "Bank withdrawals that pay an exact set of the selected groups' unpaid claims, with the fee row",
        "tags": [
          "Settlement Pack"
        ]
      }
    },
    "/api/settlement-pack/payouts/settle": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "claim_ids": {
                    "items": {
                      "format": "uuid",
                      "type": "string"
                    },
                    "type": "array"
                  },
                  "confirm": {
                    "type": "boolean"
                  },
                  "fee_transaction_id": {
                    "format": "uuid",
                    "nullable": true,
                    "type": "string"
                  },
                  "payment_document_ids": {
                    "items": {
                      "format": "uuid",
                      "type": "string"
                    },
                    "type": "array"
                  },
                  "transfer_guard": {
                    "$ref": "#/components/schemas/TransferGuard"
                  },
                  "transfer_transaction_id": {
                    "format": "uuid",
                    "type": "string"
                  }
                },
                "required": [
                  "payment_document_ids",
                  "transfer_transaction_id",
                  "claim_ids",
                  "confirm"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SettlePayoutResult"
                }
              }
            },
            "description": "Settled, or an exact replay"
          },
          "400": {
            "description": "Validation error, or a claim outside the named groups"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "A group or bank row is missing or not owned"
          },
          "409": {
            "description": "Amount does not equal the claims, a claim is already paid or stale, the company card paid a line, the transfer is already linked or booked to another account, or integrity drift"
          },
          "423": {
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetails"
                }
              }
            },
            "description": "The bank row already carries 証憑 (a document link or a file), and the 仕訳 this call attaches to it is in a filed or closed 課税期間, including a quarter whose return is filed while its period row is still open (PERIOD_LOCKED). Allowed inside a 修正申告 for that fiscal year."
          }
        },
        "summary": "Record the real transfer: link claims + 支払明細書, Dr 役員借入金 / Cr 普通預金, fee Dr 支払手数料, pay slips PAID",
        "tags": [
          "Settlement Pack"
        ]
      }
    },
    "/api/settlement-pack/preview": {
      "get": {
        "parameters": [
          {
            "explode": true,
            "in": "query",
            "name": "source_document_ids",
            "required": true,
            "schema": {
              "items": {
                "format": "uuid",
                "type": "string"
              },
              "type": "array"
            },
            "style": "form"
          },
          {
            "in": "query",
            "name": "pay_date",
            "schema": {
              "example": "2026-08-25",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SettlementPackPreview"
                }
              }
            },
            "description": "Preview"
          },
          "400": {
            "description": "Validation error"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "A named claim is missing or not owned"
          }
        },
        "summary": "Preview a grouped 支払明細書 over selected claims",
        "tags": [
          "Settlement Pack"
        ]
      }
    },
    "/api/tax-compliance-init/init": {
      "get": {
        "description": "Composite endpoint that fetches all data needed by the /tax-compliance page in a single request, eliminating the waterfall pattern.\n\n**Parallelizes:**\n1. Journal entries summary by account (総勘定元帳) — `/api/journal-entries/summary/account`\n2. Bank statements (銀行明細) — `/api/bank-statements`\n\n**Performance:**\n| Metric | Before (waterfall) | After (parallel) |\n|--------|-------------------|-----------------|\n| Requests | 2 sequential | 1 |\n| Latency | ~1880ms | ~940ms |\n\n**Caching:** Results cached in memory for 2 minutes. Stale-while-revalidate: 60s.\n\n**Graceful degradation:** If either sub-query fails, the other still returns data (failed query returns null).",
        "operationId": "getTaxComplianceInit",
        "parameters": [
          {
            "description": "Period start date in YYYYMMDD format (filters journal summary and bank statements)",
            "in": "query",
            "name": "start_date",
            "schema": {
              "example": 20250101,
              "type": "integer"
            }
          },
          {
            "description": "Period end date in YYYYMMDD format (filters journal summary and bank statements)",
            "in": "query",
            "name": "end_date",
            "schema": {
              "example": 20251231,
              "type": "integer"
            }
          },
          {
            "description": "Number of bank statement records per page (default: 20)",
            "in": "query",
            "name": "page_size",
            "schema": {
              "default": 20,
              "example": 20,
              "maximum": 100,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "description": "Page number for bank statement pagination (default: 1)",
            "in": "query",
            "name": "page_number",
            "schema": {
              "default": 1,
              "example": 1,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/TaxComplianceInitResponse"
                }
              }
            },
            "description": "Tax compliance page data fetched successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get all tax compliance page data in one request",
        "tags": [
          "Tax Compliance Init"
        ]
      }
    },
    "/api/user-activity/recent-work": {
      "get": {
        "description": "Returns server-side deduplicated recent entities from activity history. Uses PostgreSQL DISTINCT ON to return the most recent activity per unique entity, eliminating the need for client-side deduplication. 30s response cache.",
        "parameters": [
          {
            "description": "Maximum number of unique entities to return (default: 10, max: 50)",
            "in": "query",
            "name": "limit",
            "schema": {
              "default": 10,
              "maximum": 50,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "description": "Look-back window in days (default: 30, max: 90)",
            "in": "query",
            "name": "days",
            "schema": {
              "default": 30,
              "maximum": 90,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "items": {
                        "properties": {
                          "access_count": {
                            "description": "Total access count within the look-back window",
                            "example": 3,
                            "type": "integer"
                          },
                          "action_label": {
                            "example": "書類を閲覧",
                            "type": "string"
                          },
                          "action_type": {
                            "example": "document_view",
                            "type": "string"
                          },
                          "entity_id": {
                            "example": "550e8400-e29b-41d4-a716-446655440000",
                            "format": "uuid",
                            "type": "string"
                          },
                          "entity_name": {
                            "example": "請求書 #42",
                            "nullable": true,
                            "type": "string"
                          },
                          "entity_type": {
                            "description": "Entity type (document, journal_entry, client, etc.)",
                            "example": "document",
                            "type": "string"
                          },
                          "last_accessed_at": {
                            "example": "2026-02-18T05:30:00.000Z",
                            "format": "date-time",
                            "type": "string"
                          },
                          "route": {
                            "example": "/documents/550e8400-e29b-41d4-a716-446655440000",
                            "type": "string"
                          }
                        },
                        "type": "object"
                      },
                      "type": "array"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Deduplicated recent work items ordered by last access time"
          },
          "401": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "User not authenticated"
          },
          "500": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get recent work items (deduplicated)",
        "tags": [
          "User Activity"
        ]
      }
    },
    "/auditor-view/audit-pack": {
      "get": {
        "parameters": [
          {
            "description": "Fiscal year filter",
            "in": "query",
            "name": "fiscal_year",
            "required": false,
            "schema": {
              "maximum": 2100,
              "minimum": 2000,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/zip": {
                "schema": {
                  "format": "binary",
                  "type": "string"
                }
              }
            },
            "description": "ZIP download",
            "headers": {
              "Content-Disposition": {
                "description": "attachment; filename=…",
                "schema": {
                  "type": "string"
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Download audit pack ZIP (owner)",
        "tags": [
          "Auditor View"
        ]
      }
    },
    "/auditor-view/evidence-bundle": {
      "get": {
        "parameters": [
          {
            "description": "Fiscal year filter",
            "in": "query",
            "name": "fiscal_year",
            "required": false,
            "schema": {
              "maximum": 2100,
              "minimum": 2000,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/zip": {
                "schema": {
                  "format": "binary",
                  "type": "string"
                }
              }
            },
            "description": "ZIP download",
            "headers": {
              "Content-Disposition": {
                "description": "attachment; filename=…",
                "schema": {
                  "type": "string"
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Download 証憑一式 (evidence binaries) ZIP",
        "tags": [
          "Auditor View"
        ]
      }
    },
    "/auditor-view/overview": {
      "get": {
        "parameters": [
          {
            "description": "Fiscal year filter",
            "in": "query",
            "name": "fiscal_year",
            "required": false,
            "schema": {
              "maximum": 2100,
              "minimum": 2000,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                }
              }
            },
            "description": "Overview payload for the books / auditor UI"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Composed read-only auditor overview",
        "tags": [
          "Auditor View"
        ]
      }
    },
    "/auditor-view/shares": {
      "get": {
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                }
              }
            },
            "description": "Share link list (no raw tokens)"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List books share links",
        "tags": [
          "Auditor View"
        ]
      },
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateBooksShareRequest"
              }
            }
          },
          "required": false
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BooksShareCreated"
                }
              }
            },
            "description": "Share created"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create books share link (returns raw token once)",
        "tags": [
          "Auditor View"
        ]
      }
    },
    "/auditor-view/shares/{id}": {
      "delete": {
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Share revoked"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Revoke a books share link",
        "tags": [
          "Auditor View"
        ]
      }
    },
    "/auditor-view/shares/{id}/access-log": {
      "get": {
        "description": "Returns the per-access event log for one share link, ordered newest-first. Includes unlock attempts (success and failure), overview fetches, and download events.",
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "items": {
                        "$ref": "#/components/schemas/BooksShareAccessEvent"
                      },
                      "type": "array"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Access event list"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Share not found or does not belong to caller"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Who/when access log for a share link (owner only)",
        "tags": [
          "Auditor View"
        ]
      }
    },
    "/auth/debug/token": {
      "get": {
        "description": "**⚠️ Development Only** - This endpoint is only available in development mode.\n\n## Purpose\nDiagnoses authentication issues by analyzing the provided JWT token without making Supabase API calls.\n\n## What It Checks\n- **Token Presence**: Whether Authorization header is provided\n- **Token Format**: Whether it's a valid JWT structure (3 parts separated by dots)\n- **Payload Decoding**: Extracts and displays token claims (sub, exp, iat, etc.)\n- **Expiration Check**: Validates if token is expired\n- **Sub Claim**: Detects if 'sub' claim is missing (common API key mistake)\n\n## Use Cases\n- Debugging 401 authentication errors\n- Verifying token format before making API calls\n- Checking if frontend is sending correct token type\n- Diagnosing OAuth callback token issues",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "invalid-format": {
                    "summary": "Invalid JWT format",
                    "value": {
                      "formatValidation": {
                        "error": "Invalid JWT structure: expected 3 parts, got 1",
                        "isValid": false,
                        "payload": null
                      },
                      "headers": {
                        "hasCookieRefreshToken": false,
                        "hasXRefreshToken": false
                      },
                      "tokenLength": 13,
                      "tokenPreview": "invalid-token...alid-token",
                      "tokenProvided": true
                    }
                  },
                  "missing-sub": {
                    "summary": "Missing sub claim (API key used)",
                    "value": {
                      "formatValidation": {
                        "error": "Missing required \"sub\" claim - this may be an API key instead of a user token",
                        "isValid": false,
                        "payload": null
                      },
                      "headers": {
                        "hasCookieRefreshToken": false,
                        "hasXRefreshToken": false
                      },
                      "tokenLength": 256,
                      "tokenPreview": "eyJhbGciOiJIUzI1NiIs...xxx",
                      "tokenProvided": true
                    }
                  },
                  "no-token": {
                    "summary": "No token provided",
                    "value": {
                      "authenticated": false,
                      "headers": {
                        "hasAuthorization": false,
                        "hasCookieRefreshToken": false,
                        "hasXRefreshToken": false
                      },
                      "reason": "No token provided"
                    }
                  },
                  "valid-token": {
                    "summary": "Valid token format",
                    "value": {
                      "formatValidation": {
                        "error": null,
                        "isValid": true,
                        "payload": {
                          "email": "user@example.com",
                          "exp": 1704067200,
                          "expFormatted": "2024-01-01T00:00:00.000Z",
                          "iat": 1704063600,
                          "sub": "550e8400-e29b-41d4-a716-446655440000"
                        }
                      },
                      "headers": {
                        "hasCookieRefreshToken": true,
                        "hasXRefreshToken": false
                      },
                      "tokenLength": 1024,
                      "tokenPreview": "eyJhbGciOiJIUzI1NiIs...nR5cCI6IkpXVCJ9",
                      "tokenProvided": true
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/TokenDebugResponse"
                }
              }
            },
            "description": "Token analysis result"
          },
          "404": {
            "content": {
              "application/json": {
                "example": {
                  "error": "Not found"
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Endpoint not found (production mode)"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "[DEV] Debug token format and validation",
        "tags": [
          "Authentication"
        ]
      }
    },
    "/auth/debug/validate-format": {
      "post": {
        "description": "**⚠️ Development Only** - This endpoint is only available in development mode.\n\n## Purpose\nTests the token format validation logic without requiring the Authorization header.\nUseful for validating tokens from other sources or testing the validation logic itself.\n\n## Request Body\nSend the token in the request body as JSON.\n\n## What It Validates\n- JWT structure (3 parts separated by dots)\n- Base64 header format (starts with 'eyJ')\n- Payload decoding\n- Required claims (sub, exp, iat)",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "invalid-token": {
                  "summary": "Invalid token",
                  "value": {
                    "token": "not-a-valid-jwt"
                  }
                },
                "valid-token": {
                  "summary": "Valid JWT token",
                  "value": {
                    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/TokenFormatValidationRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "invalid": {
                    "summary": "Invalid token format",
                    "value": {
                      "error": "Invalid JWT structure: expected 3 parts, got 1",
                      "isValid": false,
                      "payload": null,
                      "tokenLength": 16,
                      "tokenPreview": "not-a-valid-jwt..."
                    }
                  },
                  "valid": {
                    "summary": "Valid token format",
                    "value": {
                      "error": null,
                      "isValid": true,
                      "payload": {
                        "iat": 1516239022,
                        "name": "John Doe",
                        "sub": "1234567890"
                      },
                      "tokenLength": 172,
                      "tokenPreview": "eyJhbGciOiJIUzI1NiIsInR5cC..."
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/TokenFormatValidationResponse"
                }
              }
            },
            "description": "Validation result"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Token is required in request body",
                      "type": "string"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Missing token in request body"
          },
          "404": {
            "description": "Endpoint not found (production mode)"
          }
        },
        "summary": "[DEV] Test token format validation",
        "tags": [
          "Authentication"
        ]
      }
    },
    "/auth/debug/verify": {
      "get": {
        "description": "**⚠️ Development Only** - This endpoint is only available in development mode.\n\n## Purpose\nPerforms full token verification through Supabase and returns the authenticated user's information.\n\n## What It Does\n1. Validates token format (pre-flight check)\n2. Verifies token with Supabase Auth server\n3. Returns user profile information\n4. Indicates if demo mode is active\n\n## Difference from /auth/me\n- More detailed response for debugging\n- Includes isDemo flag\n- Simpler response structure for testing",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "authenticated-user": {
                    "summary": "Authenticated real user",
                    "value": {
                      "authenticated": true,
                      "isDemo": false,
                      "message": "Token is valid and user is authenticated",
                      "success": true,
                      "user": {
                        "created_at": "2024-01-10T08:15:00.000Z",
                        "email": "user@example.com",
                        "id": "550e8400-e29b-41d4-a716-446655440000",
                        "last_sign_in_at": "2024-01-15T10:30:00.000Z",
                        "role": "authenticated"
                      }
                    }
                  },
                  "demo-user": {
                    "summary": "Demo mode authentication",
                    "value": {
                      "authenticated": true,
                      "isDemo": true,
                      "message": "Token is valid and user is authenticated",
                      "success": true,
                      "user": {
                        "email": "demo@soloboss.cloud",
                        "id": "879269ad-3298-4878-85ac-eca1e7386d6e",
                        "role": "demo"
                      }
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/TokenVerifyResponse"
                }
              }
            },
            "description": "Token verified successfully"
          },
          "401": {
            "content": {
              "application/json": {
                "examples": {
                  "invalid-format": {
                    "summary": "Invalid token format",
                    "value": {
                      "code": "INVALID_TOKEN_FORMAT",
                      "details": {
                        "hint": "Token should be a valid JWT with 3 parts"
                      },
                      "error": "Invalid JWT structure: expected 3 parts, got 1"
                    }
                  },
                  "missing-sub": {
                    "summary": "Missing sub claim",
                    "value": {
                      "code": "MISSING_SUB_CLAIM",
                      "details": {
                        "hint": "You may be using a Supabase API key instead of a user access token"
                      },
                      "error": "Missing required \"sub\" claim - this may be an API key instead of a user token"
                    }
                  },
                  "no-token": {
                    "summary": "No token provided",
                    "value": {
                      "code": "NO_TOKEN",
                      "details": {
                        "hint": "Include Authorization header with Bearer token"
                      },
                      "error": "No authentication token provided"
                    }
                  },
                  "token-expired": {
                    "summary": "Token expired",
                    "value": {
                      "code": "TOKEN_EXPIRED",
                      "details": {
                        "hint": "Re-authenticate to get new tokens"
                      },
                      "error": "Token expired and no refresh token provided"
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/AuthErrorResponse"
                }
              }
            },
            "description": "Authentication failed"
          },
          "404": {
            "description": "Endpoint not found (production mode)"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "[DEV] Verify token with Supabase and return user info",
        "tags": [
          "Authentication"
        ]
      }
    },
    "/auth/logout": {
      "post": {
        "description": "Securely logs out the authenticated user and invalidates their session and tokens.\n      \n## Logout Process\n- **Token Invalidation**: Invalidates current access and refresh tokens\n- **Session Cleanup**: Clears user session data from server\n- **Cookie Removal**: Removes authentication cookies from client\n- **Security Logging**: Records logout event for audit and security monitoring\n\n## Security Features\n- **Complete Cleanup**: Ensures all authentication artifacts are removed\n- **Audit Trail**: Maintains complete audit trail of logout events\n- **IP Tracking**: Records logout IP address for security analysis\n- **Session Security**: Prevents session hijacking after logout\n\n## Client-Side Actions\n- **Cookie Clearing**: Instructs client to remove authentication cookies\n- **Local Storage**: Client should clear any cached authentication data\n- **Redirect Handling**: Provides appropriate redirect instructions\n- **State Reset**: Ensures client application state is properly reset\n\n## Monitoring and Compliance\n- **Security Events**: Logout events logged for security monitoring\n- **Compliance**: Maintains audit logs for regulatory compliance\n- **Performance**: Tracks logout performance and success rates\n- **Error Handling**: Comprehensive error handling for logout failures",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-logout": {
                    "summary": "Successful user logout",
                    "value": {
                      "data": "Log out successfully",
                      "message": "User logged out successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/LogoutSuccessResponse"
                }
              }
            },
            "description": "User logged out successfully"
          },
          "401": {
            "content": {
              "application/json": {
                "examples": {
                  "invalid-session": {
                    "summary": "Invalid user session",
                    "value": {
                      "error": "Unauthorized",
                      "message": "Invalid user session, already logged out",
                      "statusCode": 401
                    }
                  },
                  "not-authenticated": {
                    "summary": "User not authenticated",
                    "value": {
                      "error": "Unauthorized",
                      "message": "User not authenticated",
                      "statusCode": 401
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "User not authenticated"
          },
          "500": {
            "content": {
              "application/json": {
                "examples": {
                  "logout-error": {
                    "summary": "Error during logout process",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "An unexpected error occurred during logout",
                      "statusCode": 500
                    }
                  },
                  "session-cleanup-error": {
                    "summary": "Error cleaning up user session",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "Failed to properly clean up user session",
                      "statusCode": 500
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error during logout"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Logout user and invalidate session",
        "tags": [
          "Authentication"
        ]
      }
    },
    "/auth/me": {
      "get": {
        "description": "Retrieves the current authenticated user's profile information and session status.\n      \n## Authentication Verification\n- **Token Validation**: Validates JWT access token from Authorization header\n- **Session Check**: Verifies active user session and permissions\n- **Profile Retrieval**: Fetches complete user profile from database\n- **Security Validation**: Ensures user has valid authentication status\n\n## Profile Information\n- **Basic Details**: User ID, email, display name, avatar\n- **Authentication Data**: Provider information, last sign-in timestamp\n- **Account Metadata**: Creation and update timestamps\n- **Session Status**: Current authentication status and validity\n\n## Security Features\n- **Bearer Token Required**: Requires valid JWT token in Authorization header\n- **Session Validation**: Comprehensive session security checks\n- **Rate Limiting**: Protected against abuse through authentication middleware\n- **Audit Logging**: Logs authentication check attempts for security monitoring\n\n## Use Cases\n- **Frontend Authentication**: Verify user login status on page load\n- **Profile Display**: Show user information in application UI\n- **Session Management**: Check if user session is still valid\n- **Authorization**: Verify user permissions for protected resources",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-profile-retrieval": {
                    "summary": "Successful user profile retrieval",
                    "value": {
                      "data": {
                        "avatar_url": "https://lh3.googleusercontent.com/a/default-user=s96-c",
                        "created_at": "2024-01-10T08:15:00.000Z",
                        "email": "john.doe@example.com",
                        "id": "550e8400-e29b-41d4-a716-446655440000",
                        "last_sign_in_at": "2024-01-15T10:30:00.000Z",
                        "name": "John Doe",
                        "providers": [
                          "google"
                        ],
                        "updated_at": "2024-01-15T10:30:00.000Z"
                      },
                      "message": "User profile retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/UserProfileResponse"
                }
              }
            },
            "description": "User profile retrieved successfully"
          },
          "401": {
            "content": {
              "application/json": {
                "examples": {
                  "invalid-token": {
                    "summary": "Invalid or expired JWT token",
                    "value": {
                      "error": "Unauthorized",
                      "message": "Invalid or expired authentication token",
                      "statusCode": 401
                    }
                  },
                  "missing-token": {
                    "summary": "Missing Authorization header",
                    "value": {
                      "error": "Unauthorized",
                      "message": "Authorization header is required",
                      "statusCode": 401
                    }
                  },
                  "user-not-found": {
                    "summary": "User profile not found",
                    "value": {
                      "error": "Unauthorized",
                      "message": "User profile not found or has been deleted",
                      "statusCode": 401
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "User not authenticated or invalid token"
          },
          "500": {
            "content": {
              "application/json": {
                "examples": {
                  "database-error": {
                    "summary": "Database connection error",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "Failed to retrieve user profile from database",
                      "statusCode": 500
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get authenticated user profile",
        "tags": [
          "Authentication"
        ]
      }
    },
    "/auth/me/light": {
      "get": {
        "description": "Returns only essential user data for UI header/avatar display.\n\n## Performance\n- **Latency**: ~50–100ms (single Prisma query with field selection)\n- **vs /auth/me**: ~600ms (3 parallelized queries with security score + recovery info)\n\n## Use Cases\n- **Page-load rehydration**: Fast user data for header/avatar on every page load\n- **Non-blocking login**: Fire-and-forget after login to populate header\n- **Frequent polling**: Safe to call often due to minimal DB load\n\n## When to Use Full /auth/me Instead\n- Profile/settings page (needs security score, recovery codes, backup email)\n- Account management features\n\n## Response\nReturns: id, email, name (display_name or first_name), avatarUrl — plus a top-level `csrfToken`.\n\n## CSRF piggyback (v5.20+)\nA 200 also sets the `sbc_csrf_token` cookie and returns the same value as top-level `csrfToken`, so a\nboot does not need a second round trip to the (rate-limited) `GET /api/csrf/token`. Seed the in-memory\ntoken from this field and skip that call.\n\nA LIVE token is NOT rotated: a token this server issued that has not expired is returned as-is (only its\nMax-Age is re-set, to its remaining life), because this probe is called from several places and from other\ntabs, and rotating it would 403 any tab still holding the previous value. A cookie this server did NOT\nissue — the value is signed, so a planted one is detectable — or one older than an hour IS replaced, which\nbounds how long a single value can live. `GET /api/csrf/token` still mints a fresh token and is unchanged.\nOlder clients that ignore `csrfToken` keep working.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-light-profile": {
                    "summary": "Successful lightweight profile retrieval",
                    "value": {
                      "csrfToken": "_kzczlJ6y6rlJ3n8xpak82Hd0a5SJv_bOsrSTFLcDfE.tlqo00.Npzm781CB1awR1_1c5uXhb47dQEnKqWp9NurbZ3Opt0",
                      "data": {
                        "avatarUrl": "https://lh3.googleusercontent.com/a/default-user=s96-c",
                        "email": "john.doe@example.com",
                        "id": "550e8400-e29b-41d4-a716-446655440000",
                        "name": "John Doe"
                      },
                      "message": "Success",
                      "success": true
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/UserProfileLightResponse"
                }
              }
            },
            "description": "Lightweight user profile retrieved successfully (sets the sbc_csrf_token cookie)",
            "headers": {
              "Set-Cookie": {
                "description": "sbc_csrf_token=<csrfToken>; Max-Age=<remaining life, at most 3600>; Path=/; Secure; SameSite=None (httpOnly: false — readable by the double-submit client)",
                "schema": {
                  "type": "string"
                }
              }
            }
          },
          "401": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AuthErrorResponse"
                }
              }
            },
            "description": "Not authenticated"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "User profile not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get lightweight user profile (name + avatar only)",
        "tags": [
          "Authentication"
        ]
      }
    },
    "/auth/oauth/callback": {
      "post": {
        "description": "Processes OAuth tokens from Google and completes the authentication flow.\n      \n## OAuth Token Processing\n- **Token Validation**: Validates OAuth tokens received from Google\n- **User Verification**: Extracts and verifies user information from Google\n- **Profile Management**: Creates new user profiles or updates existing ones\n- **Token Issuance**: Issues JWT access and refresh tokens for API access\n\n## User Profile Creation\n- **New User Detection**: Automatically detects first-time users\n- **Profile Initialization**: Creates comprehensive user profile with default settings\n- **Metadata Capture**: Records authentication metadata (IP, user agent, timestamp)\n- **Provider Tracking**: Links authentication method to user profile\n\n## Security Implementation\n- **Token Validation**: Comprehensive validation of OAuth tokens\n- **IP Tracking**: Records authentication IP for security monitoring\n- **User Agent Logging**: Captures browser/device information for audit\n- **Session Security**: Implements secure session management practices\n\n## Audit and Monitoring\n- **Authentication Logging**: Detailed logs for successful and failed attempts\n- **Performance Tracking**: Monitors authentication flow performance\n- **Security Events**: Comprehensive security event logging\n- **Error Tracking**: Detailed error logging for troubleshooting",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "oauth-tokens": {
                  "summary": "OAuth tokens from Google",
                  "value": {
                    "access_token": "ya29.a0AfH6SMCxyz123...",
                    "expires_in": 3600,
                    "refresh_token": "1//0GWThWrMpn5s2CgYIARAAGAwSNwF..."
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/OAuthCallbackRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-authentication": {
                    "description": "Note: The refresh token is NOT in the response body. It is set as an httpOnly cookie via the Set-Cookie header.",
                    "summary": "Successful OAuth processing",
                    "value": {
                      "data": {
                        "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
                        "expiresIn": 3600
                      },
                      "message": "Authentication successful",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/AuthTokenResponse"
                }
              }
            },
            "description": "Authentication successful, tokens issued"
          },
          "400": {
            "content": {
              "application/json": {
                "examples": {
                  "invalid-tokens": {
                    "summary": "Invalid or expired OAuth tokens",
                    "value": {
                      "error": "Bad Request",
                      "message": "Invalid or expired OAuth tokens provided",
                      "statusCode": 400
                    }
                  },
                  "missing-tokens": {
                    "summary": "Missing required token fields",
                    "value": {
                      "error": "Validation Error",
                      "message": "access_token, refresh_token, and expires_in are required",
                      "statusCode": 400
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Invalid OAuth tokens or request format"
          },
          "401": {
            "content": {
              "application/json": {
                "examples": {
                  "auth-failed": {
                    "summary": "Google authentication failed",
                    "value": {
                      "error": "Unauthorized",
                      "message": "Failed to authenticate with Google OAuth",
                      "statusCode": 401
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "OAuth authentication failed"
          },
          "500": {
            "content": {
              "application/json": {
                "examples": {
                  "profile-creation-error": {
                    "summary": "Error creating user profile",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "Failed to create user profile after authentication",
                      "statusCode": 500
                    }
                  },
                  "token-generation-error": {
                    "summary": "Error generating JWT tokens",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "Failed to generate authentication tokens",
                      "statusCode": 500
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error during authentication"
          }
        },
        "summary": "Process OAuth callback and issue authentication tokens",
        "tags": [
          "Authentication"
        ]
      }
    },
    "/auth/oauth/google": {
      "get": {
        "description": "Generates a Google OAuth 2.0 authorization URL for user authentication.\n      \n## OAuth Flow Initiation\n- **Frontend URL Detection**: Automatically detects the frontend URL from request headers\n- **State Management**: Generates secure state parameter for CSRF protection\n- **Scope Configuration**: Requests appropriate Google API scopes (openid, email, profile)\n- **Redirect URL**: Configures proper callback URL for OAuth completion\n\n## Security Features\n- **CSRF Protection**: Includes state parameter to prevent cross-site request forgery\n- **Secure Redirects**: Validates and sanitizes redirect URLs\n- **Audit Logging**: Logs OAuth initiation attempts with IP and user agent\n- **Rate Limiting**: Protected against abuse through rate limiting middleware\n\n## Integration Points\n- **Google OAuth 2.0**: Official Google authentication service\n- **Supabase Auth**: Backend authentication service integration\n- **Frontend Coordination**: Seamless integration with frontend authentication flow\n- **Security Monitoring**: Comprehensive logging for security analysis\n\n## Response Handling\n- **Authorization URL**: Returns complete Google OAuth URL for user redirection\n- **Frontend Integration**: URL can be used directly for window.location or iframe\n- **Error Handling**: Comprehensive error responses for troubleshooting\n- **Logging**: Security events logged for monitoring and audit",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-initiation": {
                    "summary": "Successful OAuth URL generation",
                    "value": {
                      "data": "https://accounts.google.com/oauth/authorize?client_id=123456789.apps.googleusercontent.com&redirect_uri=https://yourapp.com/auth/callback&response_type=code&scope=openid+email+profile&state=random-state-string",
                      "message": "Google login URL generated successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/GoogleLoginInitiationResponse"
                }
              }
            },
            "description": "Google OAuth URL generated successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "examples": {
                  "invalid-frontend-url": {
                    "summary": "Invalid frontend URL detected",
                    "value": {
                      "error": "Bad Request",
                      "message": "Invalid or missing frontend URL in request headers",
                      "statusCode": 400
                    }
                  },
                  "oauth-config-error": {
                    "summary": "OAuth configuration error",
                    "value": {
                      "error": "Configuration Error",
                      "message": "Google OAuth configuration is invalid or missing",
                      "statusCode": 400
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Invalid request or configuration error"
          },
          "500": {
            "content": {
              "application/json": {
                "examples": {
                  "server-error": {
                    "summary": "OAuth service error",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "An unexpected error occurred while generating OAuth URL",
                      "statusCode": 500
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error"
          }
        },
        "summary": "Initiate Google OAuth login flow",
        "tags": [
          "Authentication"
        ]
      }
    },
    "/auth/refresh": {
      "post": {
        "description": "Refreshes expired JWT access tokens using a valid refresh token to maintain user sessions.\n      \n## Token Refresh Process\n- **Refresh Token Validation**: Validates refresh token from secure httpOnly cookie\n- **Session Verification**: Ensures user session is still valid and active\n- **New Token Generation**: Issues new access and refresh token pair\n- **Security Rotation**: Implements token rotation for enhanced security\n\n## Cookie-Based Security\n- **HttpOnly Cookies**: Refresh tokens stored in secure httpOnly cookies\n- **CSRF Protection**: Protects against cross-site request forgery attacks\n- **Secure Transmission**: Cookies marked as secure for HTTPS-only transmission\n- **SameSite Policy**: Implements SameSite cookie policy for additional security\n\n## Session Management\n- **Automatic Renewal**: Seamless token renewal without user interaction\n- **Session Continuity**: Maintains user session across token expiration\n- **Security Monitoring**: Logs token refresh attempts for security analysis\n- **Failure Handling**: Graceful handling of invalid or expired refresh tokens\n\n## Error Scenarios\n- **Missing Refresh Token**: When refresh token cookie is not present\n- **Invalid Token**: When refresh token is malformed or expired\n- **Session Expired**: When user session has been invalidated\n- **Security Violations**: When suspicious refresh attempts are detected",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-refresh": {
                    "description": "Note: The new rotated refresh token is NOT in the response body. It is set as an httpOnly cookie via the Set-Cookie header. The frontend should call supabase.auth.setSession({ access_token, refresh_token: \"backend-managed\" }) to sync the Supabase client.",
                    "summary": "Successful token refresh",
                    "value": {
                      "data": {
                        "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
                        "expiresIn": 3600
                      },
                      "message": "Tokens refreshed successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/AuthTokenResponse"
                }
              }
            },
            "description": "Tokens refreshed successfully"
          },
          "401": {
            "content": {
              "application/json": {
                "examples": {
                  "invalid-refresh-token": {
                    "summary": "Invalid or expired refresh token",
                    "value": {
                      "error": "Unauthorized",
                      "message": "Invalid or expired refresh token",
                      "statusCode": 401
                    }
                  },
                  "missing-refresh-token": {
                    "summary": "No refresh token provided",
                    "value": {
                      "error": "Unauthorized",
                      "message": "No refresh token provided",
                      "statusCode": 401
                    }
                  },
                  "session-expired": {
                    "summary": "User session has expired",
                    "value": {
                      "error": "Unauthorized",
                      "message": "User session has expired, please log in again",
                      "statusCode": 401
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Invalid or missing refresh token"
          },
          "500": {
            "content": {
              "application/json": {
                "examples": {
                  "session-validation-error": {
                    "summary": "Error validating user session",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "Invalid session data received",
                      "statusCode": 500
                    }
                  },
                  "token-generation-error": {
                    "summary": "Error generating new tokens",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "Failed to generate new authentication tokens",
                      "statusCode": 500
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error during token refresh"
          }
        },
        "summary": "Refresh expired authentication tokens",
        "tags": [
          "Authentication"
        ]
      }
    },
    "/auth/sessions": {
      "get": {
        "description": "Returns browser/device sessions for the authenticated user. Settings UI is not wired yet; API is live.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "sessions": {
                      "items": {
                        "properties": {
                          "current": {
                            "type": "boolean"
                          },
                          "id": {
                            "format": "uuid",
                            "type": "string"
                          },
                          "lastSeenAt": {
                            "format": "date-time",
                            "type": "string"
                          },
                          "userAgent": {
                            "type": "string"
                          }
                        },
                        "type": "object"
                      },
                      "type": "array"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Active sessions"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List active sessions for the current user",
        "tags": [
          "Authentication"
        ]
      }
    },
    "/auth/sessions/signout-others": {
      "post": {
        "description": "Keeps the current session; revokes other devices.",
        "responses": {
          "200": {
            "description": "Other sessions signed out"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Sign out all other sessions",
        "tags": [
          "Authentication"
        ]
      }
    },
    "/auth/sessions/{id}": {
      "delete": {
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Session revoked"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Session not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Revoke a specific session",
        "tags": [
          "Authentication"
        ]
      }
    },
    "/auth/validate": {
      "get": {
        "description": "Validates the access token using local JWKS verification only. No database queries, no token rotation.\n\n## Performance\n- **Latency**: ~1–5ms (local JWKS verification via authMiddleware fast path)\n- **No DB queries**: Zero database load\n- **No token rotation**: Refresh token is NOT consumed or rotated\n\n## Use Cases\n- **Page-load validation**: Check if access token is still valid before making API calls\n- **Pre-flight check**: Verify token before expensive operations\n- **Health check**: Quick auth status verification\n\n## How It Works\n1. authMiddleware verifies the JWT using cached JWKS public keys (~1–5ms)\n2. If valid, this endpoint returns `{ valid: true, expiresAt, expiresIn }`\n3. If invalid/expired, authMiddleware returns 401 before this endpoint runs\n\n## When to Use /auth/refresh Instead\n- Token is expired and needs rotation\n- You need a new access token (not just validation)",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "valid-token": {
                    "summary": "Token validated successfully",
                    "value": {
                      "data": {
                        "expiresAt": 1704067200,
                        "expiresIn": 3540,
                        "userId": "550e8400-e29b-41d4-a716-446655440000",
                        "valid": true
                      },
                      "message": "Token validated successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/TokenValidationResponse"
                }
              }
            },
            "description": "Token is valid"
          },
          "401": {
            "content": {
              "application/json": {
                "examples": {
                  "invalid-token": {
                    "summary": "Invalid token format",
                    "value": {
                      "code": "INVALID_TOKEN_FORMAT",
                      "error": "Invalid JWT structure"
                    }
                  },
                  "token-expired": {
                    "summary": "Access token expired",
                    "value": {
                      "code": "TOKEN_EXPIRED",
                      "error": "Token expired and no refresh token provided"
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/AuthErrorResponse"
                }
              }
            },
            "description": "Token is invalid or expired"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Ultra-fast token validation (JWKS only, no DB queries)",
        "tags": [
          "Authentication"
        ]
      }
    },
    "/bank-accounts/settings": {
      "delete": {
        "description": "Remove bank account settings for the authenticated user.\n\n## Query Parameters\n- **company_id**: Optional company identifier for multi-company scenarios\n\n## Deletion Behavior\n- Permanently removes bank account settings from the database\n- Returns success even if no settings existed\n- Cannot be undone - user must reconfigure if needed\n\n## Impact of Deletion\nRemoving bank account settings will affect:\n- Payment processing capabilities\n- Invoice generation with bank details\n- Financial reporting and reconciliation\n- Automated payment workflows\n\n## Security Considerations\n- Operation is logged for audit purposes\n- Requires valid authentication\n- Immediate effect - no soft delete\n\n## Use Cases\n- Account cleanup and privacy\n- Company account restructuring\n- Migration to different banking arrangements\n- Compliance with data retention policies\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Optional company identifier for multi-company scenarios",
            "in": "query",
            "name": "company_id",
            "required": false,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BankAccountSettingsDeleteResponse"
                }
              }
            },
            "description": "Bank account settings deleted successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Delete bank account settings",
        "tags": [
          "Bank Account Settings"
        ]
      },
      "get": {
        "description": "Retrieve the current user's bank account settings for payment processing and financial operations.\n\n## Query Parameters\n- **company_id**: Optional company identifier for multi-company scenarios\n\n## Response Behavior\n- Returns bank account settings if configured\n- Returns null data if no settings exist (still 200 status)\n- Settings include Japanese banking format validation\n\n## Japanese Banking Standards\nThis endpoint supports Japanese banking system requirements:\n- **Bank codes**: 4-digit numerical codes identifying financial institutions\n- **Branch codes**: 3-digit numerical codes identifying bank branches  \n- **Account types**: 普通 (savings), 当座 (checking), 貯蓄 (deposit)\n- **Account numbers**: 7-8 digit numerical account identifiers\n\n## Use Cases\n- Payment processing setup\n- Invoice generation with bank details\n- Financial reporting and reconciliation\n- Multi-company bank account management\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Optional company identifier for multi-company scenarios",
            "in": "query",
            "name": "company_id",
            "required": false,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BankAccountSettingsResponse"
                }
              }
            },
            "description": "Bank account settings retrieved successfully (may be null if not configured)"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get user bank account settings",
        "tags": [
          "Bank Account Settings"
        ]
      },
      "put": {
        "description": "Create new bank account settings or update existing ones for the authenticated user.\n\n## Request Body\nAll fields follow Japanese banking standards with proper validation:\n- **bank_name** and **account_holder_name** are required\n- **bank_code** must be exactly 4 digits (e.g., \"0001\" for Mizuho Bank)\n- **branch_code** must be exactly 3 digits\n- **account_number** must be 7-8 digits\n- **account_type** must be one of: 普通, 当座, 貯蓄\n\n## Upsert Behavior\n- Creates new settings if none exist for the user/company combination\n- Updates existing settings if they already exist\n- Returns the complete updated settings object\n\n## Japanese Banking Integration\nSupports full Japanese banking system requirements:\n- Major bank codes (0001=Mizuho, 0005=Mitsubishi UFJ, etc.)\n- Standard branch code format\n- Proper account type classifications\n- Account number format validation\n\n## Use Cases\n- Initial bank account setup\n- Updating payment details\n- Multi-company bank account configuration\n- Integration with Japanese payment systems\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateOrUpdateBankAccountSettingsRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BankAccountSettingsUpdateResponse"
                }
              }
            },
            "description": "Bank account settings updated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update or create bank account settings",
        "tags": [
          "Bank Account Settings"
        ]
      }
    },
    "/bank-statements": {
      "get": {
        "description": "Retrieve bank statements for the authenticated user with comprehensive filtering and pagination options.\n\n## Bank Statement Retrieval (銀行取引明細取得)\nComprehensive bank statement management with:\n- **Pagination Support**: Efficient navigation through large transaction datasets\n- **Date Range Filtering**: Filter transactions by specific date ranges\n- **Transaction Categorization**: Organized by financial categories (sales, expenses, etc.)\n- **Japanese Banking Integration**: Full support for Japanese banking standards\n- **Counterparty Information**: Complete counterparty details for transaction tracking\n- **Duplicate Detection**: Identification and handling of duplicate transactions\n\n## Query Parameters\n- **Pagination**: `page_number` and `page_size` for efficient data retrieval\n- **Date Filtering**: `start_date` and `end_date` in YYYYMMDD format\n- **Sorting (v4.71+)**: Configurable with `sort_by` and `sort_order` params. Defaults to newest first (DESC)\n- **User Isolation**: Automatic filtering by authenticated user context\n\n## Sorting Options (v4.71+)\nUse `sort_by` and `sort_order` query parameters to control result ordering:\n- `sort_by=transaction_date` (default): Sort by transaction date (YYYYMMDD)\n- `sort_by=created_at`: Sort by import/creation time (useful for recently imported data)\n- `sort_order=desc` (default): Newest first (recommended for financial data UX)\n- `sort_order=asc`: Oldest first (for historical reports)\n\n**Example - Newest transactions first:**\n```\nGET /api/bank-statements?page_size=50&sort_order=desc\n```\n\n**Example - Sort by import time:**\n```\nGET /api/bank-statements?page_size=50&sort_by=created_at&sort_order=desc\n```\n\n## Fetch All Records (Duplicate Detection Mode)\nUse `limit=0` or `page_size=0` to fetch all records for duplicate detection.\n\n**Safety Limits:**\n- Maximum 50,000 records per request (prevents memory exhaustion)\n- If truncated, response includes `_meta.truncated: true`\n- Use date filters to narrow large datasets\n\n## Transaction Categories\n- **SALES (0)**: Sales revenue and income transactions\n- **EXPENSE (1)**: Business expenses and operational costs\n- **SALARY (2)**: Salary payments and compensation\n- **TAX (3)**: Tax payments and government transactions\n- **TRANSFER (4)**: Bank transfers and account movements\n- **LOANS (5)**: Loan payments and financing transactions\n- **OTHER (6)**: Miscellaneous transactions not fitting other categories\n\n## Japanese Banking Features\n- **Counterparty Details**: Bank codes, branch codes, account numbers\n- **Japanese Names**: Full support for Japanese counterparty names\n- **Banking Standards**: Compliance with Japanese banking data formats\n- **Transaction Descriptions**: Native Japanese transaction descriptions\n\n## Use Cases\n- **Financial Reporting**: Generate comprehensive financial reports\n- **Transaction Analysis**: Analyze spending patterns and income sources\n- **Accounting Integration**: Prepare data for accounting system integration\n- **Audit Preparation**: Organize transactions for audit and compliance review\n- **Cash Flow Management**: Monitor cash flow and account balances\n\n## Inline Linked Counts (v4.27+)\nUse `include_linked_counts=true` to fetch document link counts and journal status inline with each transaction.\nThis eliminates the need for a separate `/linked-counts` API call, improving performance.\n\nEach item will include a `linkedCounts` field with:\n- `documentCount`: Number of linked documents\n- `hasJournal`: Whether a journal entry exists\n- `processingStatus`: 'unprocessed' | 'journal_only' | 'doc_only' | 'complete'\n- `journalDebitAccount/Code`: Debit account details (when hasJournal is true)\n- `journalCreditAccount/Code`: Credit account details (when hasJournal is true)\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Number of statements per page. Use 0 to fetch ALL records (capped at 50,000 for safety). Default: 20",
            "example": 20,
            "in": "query",
            "name": "page_size",
            "required": false,
            "schema": {
              "default": 20,
              "minimum": 0,
              "type": "integer"
            }
          },
          {
            "deprecated": true,
            "description": "Alias for page_size (backwards compatibility). Use 0 to fetch ALL records (capped at 50,000 for safety).",
            "example": 20,
            "in": "query",
            "name": "limit",
            "required": false,
            "schema": {
              "minimum": 0,
              "type": "integer"
            }
          },
          {
            "description": "Page number for pagination",
            "example": 1,
            "in": "query",
            "name": "page_number",
            "required": false,
            "schema": {
              "default": 1,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "description": "Start date filter in YYYYMMDD format",
            "example": 20240101,
            "in": "query",
            "name": "start_date",
            "required": false,
            "schema": {
              "maximum": 99991231,
              "minimum": 19700101,
              "type": "integer"
            }
          },
          {
            "description": "End date filter in YYYYMMDD format",
            "example": 20240131,
            "in": "query",
            "name": "end_date",
            "required": false,
            "schema": {
              "maximum": 99991231,
              "minimum": 19700101,
              "type": "integer"
            }
          },
          {
            "description": "Include linked document counts and journal status inline with each transaction (v4.27+). Eliminates need for separate /linked-counts call.",
            "example": true,
            "in": "query",
            "name": "include_linked_counts",
            "required": false,
            "schema": {
              "default": false,
              "type": "boolean"
            }
          },
          {
            "description": "Field to sort results by (v4.71+). transaction_date = sort by transaction date, created_at = sort by import time.",
            "example": "transaction_date",
            "in": "query",
            "name": "sort_by",
            "required": false,
            "schema": {
              "default": "transaction_date",
              "enum": [
                "transaction_date",
                "created_at"
              ],
              "type": "string"
            }
          },
          {
            "description": "Sort direction (v4.71+). desc = newest first (recommended for financial data), asc = oldest first (for reports).",
            "example": "desc",
            "in": "query",
            "name": "sort_order",
            "required": false,
            "schema": {
              "default": "desc",
              "enum": [
                "asc",
                "desc"
              ],
              "type": "string"
            }
          },
          {
            "description": "Filter by bank account (v5.14+). Pass a UUID to filter by specific account, or the sentinel value `unassigned` to return only transactions with no linked bank account (bank_account_id IS NULL).",
            "example": "unassigned",
            "in": "query",
            "name": "bank_account_id",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "Filter by transaction source (v5.14+). `manual` = direct user entry, `csv_import` = imported from CSV file, `api_gmo_aozora` = synced via GMO Aozora API, `paste` = コピペ import of a net-bank page.",
            "example": "api_gmo_aozora",
            "in": "query",
            "name": "source",
            "required": false,
            "schema": {
              "enum": [
                "manual",
                "csv_import",
                "api_gmo_aozora",
                "paste"
              ],
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "monthly_statements": {
                    "summary": "Monthly bank statements with various transactions",
                    "value": {
                      "data": [
                        {
                          "balance": 1250000,
                          "bankAccountId": "789e0123-e45b-67c8-d901-234567890123",
                          "category": 2,
                          "counterpartyAccount": "1234567",
                          "counterpartyBankCode": "0001",
                          "counterpartyBranchCode": "123",
                          "counterpartyName": "タナカ タロウ",
                          "createdAt": "2024-01-15T10:30:00.000Z",
                          "depositAmount": 300000,
                          "description": "振込 タナカ タロウ",
                          "duplicateOfId": null,
                          "id": "123e4567-e89b-12d3-a456-426614174000",
                          "importBatchId": "987e6543-f21a-43b5-c678-109876543210",
                          "importHash": "a1b2c3d4e5f6",
                          "isDuplicate": false,
                          "journalEntryId": "456e7890-f12a-34b5-c678-901234567890",
                          "memo": "Monthly salary payment",
                          "transactionDate": 20240115,
                          "userId": "abc12345-def6-7890-ghij-klmnopqrstuv",
                          "withdrawalAmount": 0
                        },
                        {
                          "balance": 1200000,
                          "bankAccountId": "789e0123-e45b-67c8-d901-234567890123",
                          "category": 6,
                          "counterpartyAccount": null,
                          "counterpartyBankCode": null,
                          "counterpartyBranchCode": null,
                          "counterpartyName": null,
                          "createdAt": "2024-01-16T08:15:00.000Z",
                          "depositAmount": 0,
                          "description": "ATM出金",
                          "duplicateOfId": null,
                          "id": "456e7890-f12a-34b5-c678-901234567890",
                          "importBatchId": "987e6543-f21a-43b5-c678-109876543210",
                          "importHash": "b2c3d4e5f6a1",
                          "isDuplicate": false,
                          "journalEntryId": null,
                          "memo": null,
                          "transactionDate": 20240116,
                          "userId": "abc12345-def6-7890-ghij-klmnopqrstuv",
                          "withdrawalAmount": 50000
                        }
                      ],
                      "message": "銀行取引を取得しました",
                      "pagination": {
                        "currentPage": 1,
                        "hasNext": true,
                        "hasPrevious": false,
                        "pageSize": 20,
                        "totalItems": 150,
                        "totalPages": 8
                      },
                      "success": true
                    }
                  },
                  "with_linked_counts": {
                    "summary": "Bank statements with inline linked counts (include_linked_counts=true)",
                    "value": {
                      "data": [
                        {
                          "balance": 1250000,
                          "bankAccountId": "789e0123-e45b-67c8-d901-234567890123",
                          "category": 2,
                          "createdAt": "2024-01-15T10:30:00.000Z",
                          "depositAmount": 300000,
                          "description": "振込 タナカ タロウ",
                          "id": "123e4567-e89b-12d3-a456-426614174000",
                          "isDuplicate": false,
                          "journalEntryId": "456e7890-f12a-34b5-c678-901234567890",
                          "linkedCounts": {
                            "documentCount": 2,
                            "hasJournal": true,
                            "journalCreditAccount": "売上高",
                            "journalCreditCode": "4001",
                            "journalDebitAccount": "普通預金",
                            "journalDebitCode": "1111",
                            "processingStatus": "complete"
                          },
                          "memo": "Monthly salary payment",
                          "transactionDate": 20240115,
                          "userId": "abc12345-def6-7890-ghij-klmnopqrstuv",
                          "withdrawalAmount": 0
                        },
                        {
                          "balance": 1200000,
                          "bankAccountId": "789e0123-e45b-67c8-d901-234567890123",
                          "category": 6,
                          "createdAt": "2024-01-16T08:15:00.000Z",
                          "depositAmount": 0,
                          "description": "ATM出金",
                          "id": "456e7890-f12a-34b5-c678-901234567890",
                          "isDuplicate": false,
                          "journalEntryId": null,
                          "linkedCounts": {
                            "documentCount": 0,
                            "hasJournal": false,
                            "processingStatus": "unprocessed"
                          },
                          "memo": null,
                          "transactionDate": 20240116,
                          "userId": "abc12345-def6-7890-ghij-klmnopqrstuv",
                          "withdrawalAmount": 50000
                        }
                      ],
                      "message": "銀行取引を取得しました",
                      "pagination": {
                        "currentPage": 1,
                        "hasNext": true,
                        "hasPrevious": false,
                        "pageSize": 20,
                        "totalItems": 150,
                        "totalPages": 8
                      },
                      "success": true
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/BankStatementListResponse"
                }
              }
            },
            "description": "Bank statements retrieved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get bank statements with pagination and filtering",
        "tags": [
          "Bank Statements"
        ]
      },
      "post": {
        "description": "Create a new bank statement transaction with comprehensive validation and duplicate detection.\n\n## Bank Statement Creation (銀行取引明細作成)\nManual bank statement creation with:\n- **Transaction Validation**: Comprehensive validation of all transaction data\n- **Category Classification**: Automatic categorization for financial reporting\n- **Duplicate Detection**: Prevention of duplicate transaction entries\n- **Balance Tracking**: Accurate balance calculation and verification\n- **Japanese Standards**: Full compliance with Japanese banking standards\n- **Audit Trail**: Complete audit trail with user context and timestamps\n\n## Transaction Data Requirements\n- **Transaction Date**: YYYYMMDD format for consistent date handling\n- **Description**: Clear transaction description (Japanese supported)\n- **Amounts**: Precise decimal handling for deposit/withdrawal amounts\n- **Balance**: Account balance after transaction\n- **Category**: Financial category for reporting and analysis\n\n## Financial Categories\n- **SALES (0)**: Revenue and income transactions\n- **EXPENSE (1)**: Business expenses and costs\n- **SALARY (2)**: Salary and compensation payments\n- **TAX (3)**: Tax payments and government transactions\n- **TRANSFER (4)**: Account transfers and movements\n- **LOANS (5)**: Loan payments and financing\n- **OTHER (6)**: Miscellaneous transactions\n\n## Validation Features\n- **Amount Validation**: Ensures either deposit or withdrawal amount is provided\n- **Balance Verification**: Validates balance calculations\n- **Date Validation**: Ensures valid transaction dates\n- **Category Validation**: Validates transaction category selection\n- **Duplicate Prevention**: Checks for existing similar transactions\n\n## Use Cases\n- **Manual Entry**: Manual entry of bank transactions\n- **Data Correction**: Correction of imported transaction data\n- **Missing Transactions**: Addition of missing transaction records\n- **Account Reconciliation**: Manual reconciliation of account balances\n- **Audit Adjustments**: Adjustments for audit and compliance requirements\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "expense_withdrawal": {
                  "summary": "Business expense withdrawal",
                  "value": {
                    "balance": 123500000,
                    "category": 1,
                    "depositAmount": 0,
                    "description": "カード決済 オフィス用品",
                    "transactionDate": 20240116,
                    "withdrawalAmount": 1500000
                  }
                },
                "salary_deposit": {
                  "summary": "Salary deposit transaction",
                  "value": {
                    "balance": 125000000,
                    "category": 2,
                    "depositAmount": 30000000,
                    "description": "振込 タナカ タロウ",
                    "transactionDate": 20240115,
                    "withdrawalAmount": 0
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/CreateBankStatementRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "examples": {
                  "created_statement": {
                    "summary": "Successfully created bank statement",
                    "value": {
                      "data": {
                        "balance": 1250000,
                        "bankAccountId": null,
                        "category": 2,
                        "counterpartyAccount": null,
                        "counterpartyBankCode": null,
                        "counterpartyBranchCode": null,
                        "counterpartyName": null,
                        "createdAt": "2024-01-15T10:30:00.000Z",
                        "depositAmount": 300000,
                        "description": "振込 タナカ タロウ",
                        "duplicateOfId": null,
                        "id": "123e4567-e89b-12d3-a456-426614174000",
                        "importBatchId": null,
                        "importHash": null,
                        "isDuplicate": false,
                        "journalEntryId": null,
                        "memo": null,
                        "transactionDate": 20240115,
                        "userId": "abc12345-def6-7890-ghij-klmnopqrstuv",
                        "withdrawalAmount": 0
                      },
                      "message": "Bank statement created successfully",
                      "statusCode": 201
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/BankStatementResponse"
                }
              }
            },
            "description": "Bank statement created successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "409": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "duplicateId": {
                      "format": "uuid",
                      "type": "string"
                    },
                    "error": {
                      "example": "Duplicate transaction detected",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Duplicate transaction detected"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create a new bank statement",
        "tags": [
          "Bank Statements"
        ]
      }
    },
    "/bank-statements/batch-linked-counts": {
      "post": {
        "description": "POST alternative to GET /bank-statements/linked-counts for large ID sets (prefer when >100 ids or URL length limits). Max practical batch size follows service limits.",
        "operationId": "batchLinkedCounts",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "ids": {
                    "description": "Transaction UUIDs",
                    "items": {
                      "format": "uuid",
                      "type": "string"
                    },
                    "type": "array"
                  }
                },
                "required": [
                  "ids"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "counts": {
                          "additionalProperties": {
                            "properties": {
                              "documentCount": {
                                "type": "integer"
                              },
                              "hasJournal": {
                                "type": "boolean"
                              },
                              "processingStatus": {
                                "nullable": true,
                                "type": "string"
                              },
                              "suggestConfidence": {
                                "type": "number"
                              },
                              "suggestReason": {
                                "type": "string"
                              },
                              "suggestedStatus": {
                                "type": "string"
                              }
                            },
                            "type": "object"
                          },
                          "type": "object"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Per-id linked counts (+ optional AI no-doc suggestions)"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "BearerAuth": []
          }
        ],
        "summary": "Batch linked document counts (v4.28+)",
        "tags": [
          "Bank Statements"
        ]
      }
    },
    "/bank-statements/bulk": {
      "post": {
        "description": "Create multiple bank statements in a single operation with comprehensive validation and duplicate handling.\n\n## Bulk Bank Statement Creation (一括銀行取引明細作成)\nEfficient bulk creation with:\n- **Batch Processing**: Process multiple statements in a single transaction\n- **Duplicate Detection**: Advanced duplicate detection across the entire batch\n- **Partial Success**: Handle partial success scenarios with detailed reporting\n- **Transaction Integrity**: Ensure data consistency across all operations\n- **Performance Optimization**: Optimized for large batch processing\n- **Comprehensive Reporting**: Detailed success and failure reporting\n\n## Batch Processing Features\n- **Array Validation**: Validates entire array of statements before processing\n- **Atomic Operations**: Ensures all-or-nothing processing where appropriate\n- **Duplicate Handling**: Identifies and reports duplicates within batch and existing data\n- **Error Reporting**: Detailed error reporting for each failed statement\n- **Success Tracking**: Complete tracking of successfully created statements\n\n## Validation and Error Handling\n- **Individual Validation**: Each statement validated independently\n- **Batch Constraints**: Maximum batch size limits for performance\n- **Rollback Capability**: Rollback on critical errors\n- **Partial Success**: Continue processing valid statements despite individual failures\n- **Detailed Reporting**: Comprehensive success and failure reporting\n\n## Use Cases\n- **Data Migration**: Migrate historical bank statement data\n- **Bulk Import**: Import large datasets from external systems\n- **System Integration**: Integrate with external banking systems\n- **Data Reconciliation**: Bulk reconciliation of account data\n- **Historical Data Entry**: Entry of historical transaction data\n\n## Performance Considerations\n- **Batch Size Limits**: Maximum 100 statements per request\n- **Processing Time**: Optimized for efficient batch processing\n- **Memory Usage**: Efficient memory usage for large batches\n- **Database Optimization**: Optimized database operations for bulk inserts\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "monthly_transactions": {
                  "summary": "Monthly transaction batch",
                  "value": {
                    "statements": [
                      {
                        "balance": 125000000,
                        "category": 2,
                        "deposit_amount": 30000000,
                        "description": "振込 タナカ タロウ",
                        "transaction_date": 20240115,
                        "withdrawal_amount": 0
                      },
                      {
                        "balance": 120000000,
                        "category": 6,
                        "deposit_amount": 0,
                        "description": "ATM出金",
                        "transaction_date": 20240116,
                        "withdrawal_amount": 5000000
                      },
                      {
                        "balance": 119880000,
                        "category": 1,
                        "deposit_amount": 0,
                        "description": "カード決済 コンビニ",
                        "transaction_date": 20240117,
                        "withdrawal_amount": 120000
                      }
                    ]
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/BulkCreateBankStatementsRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "examples": {
                  "partial_success": {
                    "summary": "Bulk creation with some duplicates",
                    "value": {
                      "data": {
                        "created": [
                          {
                            "balance": 1250000,
                            "bank_account_id": null,
                            "category": 2,
                            "counterparty_account": null,
                            "counterparty_bank_code": null,
                            "counterparty_branch_code": null,
                            "counterparty_name": null,
                            "created_at": "2024-01-15T10:30:00.000Z",
                            "deposit_amount": 300000,
                            "description": "振込 タナカ タロウ",
                            "duplicate_of_id": null,
                            "id": "123e4567-e89b-12d3-a456-426614174000",
                            "import_batch_id": "987e6543-f21a-43b5-c678-109876543210",
                            "import_hash": "a1b2c3d4e5f6",
                            "is_duplicate": false,
                            "journal_entry_id": null,
                            "memo": null,
                            "transaction_date": 20240115,
                            "user_id": "abc12345-def6-7890-ghij-klmnopqrstuv",
                            "withdrawal_amount": 0
                          }
                        ],
                        "duplicates": [
                          {
                            "index": 1,
                            "reason": "Duplicate transaction with same date, amount, and description"
                          }
                        ],
                        "summary": {
                          "created": 2,
                          "duplicates": 1,
                          "total_requested": 3
                        }
                      },
                      "message": "Bank statements created successfully",
                      "statusCode": 201
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/BulkBankStatementResponse"
                }
              }
            },
            "description": "Bank statements created successfully (may include duplicates)"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "413": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Batch size exceeds maximum limit of 100 statements",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Batch size too large"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Bulk create multiple bank statements",
        "tags": [
          "Bank Statements"
        ]
      }
    },
    "/bank-statements/bulk-assign-account": {
      "patch": {
        "description": "Reassign multiple bank statement transactions to a different bank account in a single operation.\n\n## Bulk Account Assignment (一括口座割当)\nUsed to:\n- Assign orphan transactions (bank_account_id IS NULL) to an account after multi-account migration\n- Move transactions between accounts when account structure changes\n- Clean up unassigned transactions shown in the \"未割当\" filter\n\n## Validation\n- All transaction IDs must belong to the authenticated user\n- Target bank account must belong to the authenticated user\n- Maximum 500 transactions per request\n\n## CSRF Protection\nThis endpoint requires a valid CSRF token (X-CSRF-Token header matching sbc_csrf_token cookie).\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "bank_account_id": {
                    "description": "Target bank account ID to assign transactions to",
                    "example": "789e0123-e45b-67c8-d901-234567890123",
                    "format": "uuid",
                    "type": "string"
                  },
                  "transaction_ids": {
                    "description": "Array of bank statement transaction IDs to reassign",
                    "example": [
                      "123e4567-e89b-12d3-a456-426614174000",
                      "456e7890-f12a-34b5-c678-901234567890"
                    ],
                    "items": {
                      "format": "uuid",
                      "type": "string"
                    },
                    "maxItems": 500,
                    "minItems": 1,
                    "type": "array"
                  }
                },
                "required": [
                  "transaction_ids",
                  "bank_account_id"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "partial": {
                    "summary": "Partial update (some IDs not found or not owned)",
                    "value": {
                      "data": {
                        "bank_account_id": "789e0123-e45b-67c8-d901-234567890123",
                        "requested_count": 45,
                        "updated_count": 40
                      },
                      "message": "Transactions reassigned successfully",
                      "statusCode": 200
                    }
                  },
                  "success": {
                    "summary": "All transactions reassigned",
                    "value": {
                      "data": {
                        "bank_account_id": "789e0123-e45b-67c8-d901-234567890123",
                        "requested_count": 45,
                        "updated_count": 45
                      },
                      "message": "Transactions reassigned successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "bank_account_id": {
                          "description": "Target account ID",
                          "format": "uuid",
                          "type": "string"
                        },
                        "requested_count": {
                          "description": "Number of transaction IDs in request",
                          "example": 50,
                          "type": "integer"
                        },
                        "updated_count": {
                          "description": "Number of transactions actually updated",
                          "example": 45,
                          "type": "integer"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Transactions reassigned successfully",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Transactions reassigned successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "ERR_3001",
                      "type": "string"
                    },
                    "message": {
                      "example": "Validation failed",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 400,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Validation error (empty array, too many IDs, invalid bank_account_id)"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "ERR_2003",
                      "type": "string"
                    },
                    "message": {
                      "example": "CSRF validation failed",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 403,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "CSRF token missing or invalid"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Bulk assign transactions to a bank account (v5.14+)",
        "tags": [
          "Bank Statements"
        ]
      }
    },
    "/bank-statements/bulk-processing-status": {
      "patch": {
        "description": "Bulk update processing status for multiple bank transactions in a single request.\n\n## Bulk Processing Status Update (一括処理ステータス更新)\nUpdate multiple transactions at once:\n- **Batch Operations**: Update up to 100 transactions per request\n- **Bank Fees**: Mark all bank fees as 'no_doc_required'\n- **Interest**: Mark interest transactions as 'no_doc_required'\n- **Audit Trail**: All updates are logged to audit_logs table\n\n## Use Cases\n- Mark all bank transfer fees as no_doc_required\n- Mark all interest income as no_doc_required\n- Mark ATM fees as no_doc_required\n- Bulk reset to derived status (null)\n\n## Limits\n- Maximum 100 transaction IDs per request\n- All transactions must belong to the authenticated user\n\n## Audit Logging\nEach update creates an audit log entry with:\n- Old status\n- New status\n- Transaction description (truncated)\n- Bulk operation flag\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "clear_statuses": {
                  "description": "Reset to derived behavior",
                  "summary": "Clear explicit statuses",
                  "value": {
                    "processing_status": null,
                    "transaction_ids": [
                      "550e8400-e29b-41d4-a716-446655440001"
                    ]
                  }
                },
                "mark_fees_no_doc": {
                  "description": "Mark multiple bank fees as not requiring documents",
                  "summary": "Mark bank fees as no_doc_required",
                  "value": {
                    "processing_status": "no_doc_required",
                    "transaction_ids": [
                      "550e8400-e29b-41d4-a716-446655440001",
                      "550e8400-e29b-41d4-a716-446655440002",
                      "550e8400-e29b-41d4-a716-446655440003"
                    ]
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/BulkUpdateProcessingStatusRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "all_success": {
                    "summary": "All transactions updated successfully",
                    "value": {
                      "data": {
                        "failedCount": 0,
                        "results": [
                          {
                            "effectiveStatus": "no_doc_required",
                            "oldStatus": null,
                            "success": true,
                            "transactionId": "550e8400-e29b-41d4-a716-446655440001"
                          },
                          {
                            "effectiveStatus": "no_doc_required",
                            "oldStatus": "unprocessed",
                            "success": true,
                            "transactionId": "550e8400-e29b-41d4-a716-446655440002"
                          },
                          {
                            "effectiveStatus": "no_doc_required",
                            "oldStatus": null,
                            "success": true,
                            "transactionId": "550e8400-e29b-41d4-a716-446655440003"
                          }
                        ],
                        "updatedCount": 3
                      },
                      "message": "Updated 3 transactions",
                      "statusCode": 200
                    }
                  },
                  "partial_success": {
                    "summary": "Some transactions not found",
                    "value": {
                      "data": {
                        "failedCount": 1,
                        "results": [
                          {
                            "effectiveStatus": "no_doc_required",
                            "success": true,
                            "transactionId": "550e8400-e29b-41d4-a716-446655440001"
                          },
                          {
                            "effectiveStatus": "no_doc_required",
                            "success": true,
                            "transactionId": "550e8400-e29b-41d4-a716-446655440002"
                          },
                          {
                            "error": "Transaction not found",
                            "success": false,
                            "transactionId": "invalid-uuid-not-found"
                          }
                        ],
                        "updatedCount": 2
                      },
                      "message": "Updated 2 transactions, 1 failed",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/BulkUpdateProcessingStatusResponse"
                }
              }
            },
            "description": "Bulk update completed"
          },
          "400": {
            "content": {
              "application/json": {
                "examples": {
                  "batch_too_large": {
                    "summary": "Batch size exceeded",
                    "value": {
                      "message": "Batch size 150 exceeds maximum of 100 IDs per request",
                      "statusCode": 400
                    }
                  },
                  "invalid_status": {
                    "summary": "Invalid processing status",
                    "value": {
                      "message": "processing_status must be one of: unprocessed, journal_only, doc_only, complete, no_doc_required, or null to clear",
                      "statusCode": 400
                    }
                  }
                }
              }
            },
            "description": "Invalid request (batch size exceeded or invalid status)"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Bulk update processing status for multiple transactions (v4.34+)",
        "tags": [
          "Bank Statements"
        ]
      }
    },
    "/bank-statements/bulk-reimbursement": {
      "patch": {
        "description": "Batch update reimbursement status for multiple transactions. Max 100 IDs per request.",
        "operationId": "bulkUpdateReimbursement",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "reimbursement_notes": {
                    "maxLength": 2000,
                    "type": "string"
                  },
                  "reimbursement_status": {
                    "enum": [
                      "pending",
                      "submitted",
                      "approved",
                      "paid",
                      "rejected",
                      "cancelled"
                    ],
                    "type": "string"
                  },
                  "transaction_ids": {
                    "items": {
                      "format": "uuid",
                      "type": "string"
                    },
                    "maxItems": 100,
                    "type": "array"
                  }
                },
                "required": [
                  "transaction_ids",
                  "reimbursement_status"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "failed_count": {
                          "type": "integer"
                        },
                        "results": {
                          "items": {
                            "properties": {
                              "error": {
                                "nullable": true,
                                "type": "string"
                              },
                              "success": {
                                "type": "boolean"
                              },
                              "transaction_id": {
                                "format": "uuid",
                                "type": "string"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        },
                        "success_count": {
                          "type": "integer"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Bulk update results"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "BearerAuth": []
          }
        ],
        "summary": "Bulk update reimbursement status (v5.15+)",
        "tags": [
          "Bank Statements"
        ]
      }
    },
    "/bank-statements/bulk-restore": {
      "post": {
        "description": "Counterpart of bulk-delete. Up to 100 ids. Idempotent — already-restored rows return success:true for undo flows.",
        "operationId": "bulkRestoreBankStatements",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "transaction_ids": {
                    "items": {
                      "format": "uuid",
                      "type": "string"
                    },
                    "maxItems": 100,
                    "minItems": 1,
                    "type": "array"
                  }
                },
                "required": [
                  "transaction_ids"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "failedCount": {
                          "type": "integer"
                        },
                        "restoredCount": {
                          "type": "integer"
                        },
                        "results": {
                          "items": {
                            "properties": {
                              "error": {
                                "type": "string"
                              },
                              "success": {
                                "type": "boolean"
                              },
                              "transactionId": {
                                "format": "uuid",
                                "type": "string"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Restore results"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "BearerAuth": []
          }
        ],
        "summary": "Bulk restore soft-deleted bank statements",
        "tags": [
          "Bank Statements"
        ]
      }
    },
    "/bank-statements/import/stream": {
      "post": {
        "description": "Same body as text import; response is an SSE event stream (not a replayable JSON body). Intentionally no idempotency claim — FE double-submit is UI-gated.",
        "operationId": "importFromTextStream",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ImportFromTextRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "text/event-stream": {
                "schema": {
                  "type": "string"
                }
              }
            },
            "description": "text/event-stream of import progress / results"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "BearerAuth": []
          }
        ],
        "summary": "Import bank text as SSE stream",
        "tags": [
          "Bank Statements"
        ]
      }
    },
    "/bank-statements/import/zengin-csv": {
      "post": {
        "description": "Deterministic import of the 全銀協 入出金取引明細 CSV (GMOあおぞらネット銀行 法人口座ご利用ガイド Ver1.0.5 pp.25-27) — no AI.\n\n- The file travels as base64 (`file_base64`); Shift_JIS (CP932) and UTF-8 are both read.\n- Header / data / trailer / end records are parsed; dates are 和暦 (令和) YYMMDD. The running balance starts from 取引前残高.\n- The file is checked against its own trailer (入金・出金 件数と合計, データ・レコード件数, 取引後残高); any disagreement is a 422 with the reason.\n- The file's 銀行コード / 口座番号 must match the chosen account when the account records them (422 otherwise).\n- Rows are keyed `provider_transaction_id = <bank_account_id>:<照会番号>`, `source = csv_import`, with import_hash, one import_batch_id per commit and the CSV line as raw_description.\n- Idempotent: a row already stored (same provider id on the account, same import_hash, or the same date|balance|deposit|withdrawal) is a duplicate and never written — re-importing a file creates 0 rows.\n- `inquiry_numbers` (optional) limits a commit to those 照会番号 — the rows the user kept in the preview.",
        "operationId": "importZenginCsv",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/BankStatementZenginCsvImportRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/BankStatementZenginCsvImportResult"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Preview or commit result"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "The bank account is not the tenant’s"
          },
          "422": {
            "description": "Not a well-formed, self-consistent 全銀 statement, or not the chosen account’s statement"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Import a 全銀 入出金取引明細 CSV (preview or commit)",
        "tags": [
          "Bank Statements"
        ]
      }
    },
    "/bank-statements/init": {
      "get": {
        "description": "Composite endpoint for the bank statements page (銀行明細ページ). Fetches transactions, overview, and bank accounts in a single parallel request instead of 5 separate calls.\n\n**Parallelizes:**\n1. Paginated transactions with linked counts\n2. Bank account overview (summary + sync status)\n3. Bank accounts with latest balance\n\n**Performance:**\n| Metric | Before (waterfall) | After (parallel) |\n|--------|-------------------|-----------------|\n| Requests | 5 sequential | 1 |\n| Latency | ~2000ms+ | ~400ms |\n\n**Caching:** Memory cache 60s, stale-while-revalidate 30s, ETag supported.\n\n**Graceful degradation:** Individual sub-query failures return null/empty without blocking other data.\n\n**v5.20+:** `data.transactions` carries `unjournalizedCount` and `periodTotals` beside its `pagination` —\nthe same values as `GET /api/bank-statements`, for the same filters. Both are re-derived on a memory-cache\nhit; the rows themselves can be up to 60 s old.",
        "operationId": "getBankStatementsInit",
        "parameters": [
          {
            "description": "Transactions per page (default 20)",
            "in": "query",
            "name": "page_size",
            "schema": {
              "default": 20,
              "maximum": 100,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "description": "Page number (default 1)",
            "in": "query",
            "name": "page_number",
            "schema": {
              "default": 1,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "description": "Sort field",
            "in": "query",
            "name": "sort_by",
            "schema": {
              "default": "transaction_date",
              "enum": [
                "transaction_date",
                "created_at"
              ],
              "type": "string"
            }
          },
          {
            "description": "Sort direction",
            "in": "query",
            "name": "sort_order",
            "schema": {
              "default": "desc",
              "enum": [
                "asc",
                "desc"
              ],
              "type": "string"
            }
          },
          {
            "description": "Filter start date (YYYYMMDD)",
            "in": "query",
            "name": "start_date",
            "schema": {
              "example": 20260101,
              "type": "integer"
            }
          },
          {
            "description": "Filter end date (YYYYMMDD)",
            "in": "query",
            "name": "end_date",
            "schema": {
              "example": 20261231,
              "type": "integer"
            }
          },
          {
            "description": "Filter by bank account UUID",
            "in": "query",
            "name": "bank_account_id",
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BankStatementsInitResponse"
                }
              }
            },
            "description": "Bank statements page data"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get all bank statements page data in one request",
        "tags": [
          "Bank Statements"
        ]
      }
    },
    "/bank-statements/linked-counts": {
      "get": {
        "description": "Get linked document counts, processing status, and journal account details for multiple bank transactions in a single request.\n\n## Batch Linked Counts (一括紐付け件数取得)\nEfficient batch retrieval for list views:\n- **Document Counts**: Number of documents linked to each transaction\n- **Journal Status**: Whether transaction has a journal entry\n- **Processing Status**: Derived status (unprocessed, doc_only, journal_only, complete)\n- **Journal Account Details (v4.26+)**: Debit/credit account names and codes when journal exists\n\n## N+1 Optimization (v4.26+)\nThis endpoint now includes journal account details directly, eliminating the need for N+1 API calls:\n- `journalDebitAccount`: Name of the debit account (e.g., \"普通預金\")\n- `journalDebitCode`: Code of the debit account (e.g., \"1111\")\n- `journalCreditAccount`: Name of the credit account (e.g., \"売上高\")\n- `journalCreditCode`: Code of the credit account (e.g., \"4001\")\n\nThese fields are only present when `hasJournal: true`.\n\n## Use Cases\n- **List View Badges**: Show document count badges on transaction list\n- **Progress Tracking**: Display processing status without N+1 queries\n- **Account Display**: Show journal account names directly in list view\n- **Efficient Rendering**: Single request instead of one per transaction\n\n## Response Format\nReturns counts keyed by transaction ID:\n```json\n{\n  \"counts\": {\n    \"tx-uuid-1\": { \n      \"documentCount\": 2, \n      \"hasJournal\": true, \n      \"processingStatus\": \"complete\",\n      \"journalDebitAccount\": \"普通預金\",\n      \"journalDebitCode\": \"1111\",\n      \"journalCreditAccount\": \"売上高\",\n      \"journalCreditCode\": \"4001\"\n    },\n    \"tx-uuid-2\": { \"documentCount\": 0, \"hasJournal\": false, \"processingStatus\": \"unprocessed\" }\n  }\n}\n```\n",
        "operationId": "getBankStatementLinkedCounts",
        "parameters": [
          {
            "description": "Comma-separated list of bank transaction UUIDs",
            "in": "query",
            "name": "ids",
            "required": true,
            "schema": {
              "example": "uuid-1,uuid-2,uuid-3",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "example": {
                  "data": {
                    "counts": {
                      "550e8400-e29b-41d4-a716-446655440001": {
                        "documentCount": 2,
                        "hasJournal": true,
                        "journalCreditAccount": "売上高",
                        "journalCreditCode": "4001",
                        "journalDebitAccount": "普通預金",
                        "journalDebitCode": "1111",
                        "processingStatus": "complete"
                      },
                      "550e8400-e29b-41d4-a716-446655440002": {
                        "documentCount": 1,
                        "hasJournal": false,
                        "processingStatus": "doc_only"
                      },
                      "550e8400-e29b-41d4-a716-446655440003": {
                        "documentCount": 0,
                        "hasJournal": true,
                        "journalCreditAccount": "普通預金",
                        "journalCreditCode": "1111",
                        "journalDebitAccount": "買掛金",
                        "journalDebitCode": "2120",
                        "processingStatus": "journal_only"
                      },
                      "550e8400-e29b-41d4-a716-446655440004": {
                        "documentCount": 0,
                        "hasJournal": false,
                        "processingStatus": "unprocessed"
                      }
                    }
                  },
                  "message": "Linked counts retrieved successfully",
                  "success": true
                },
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "counts": {
                          "additionalProperties": {
                            "properties": {
                              "documentCount": {
                                "example": 2,
                                "type": "integer"
                              },
                              "hasJournal": {
                                "example": true,
                                "type": "boolean"
                              },
                              "journalCreditAccount": {
                                "description": "Credit account name (only present when hasJournal is true)",
                                "example": "売上高",
                                "type": "string"
                              },
                              "journalCreditCode": {
                                "description": "Credit account code (only present when hasJournal is true)",
                                "example": "4001",
                                "type": "string"
                              },
                              "journalDebitAccount": {
                                "description": "Debit account name (only present when hasJournal is true)",
                                "example": "普通預金",
                                "type": "string"
                              },
                              "journalDebitCode": {
                                "description": "Debit account code (only present when hasJournal is true)",
                                "example": "1111",
                                "type": "string"
                              },
                              "processingStatus": {
                                "enum": [
                                  "unprocessed",
                                  "journal_only",
                                  "doc_only",
                                  "complete"
                                ],
                                "example": "complete",
                                "type": "string"
                              }
                            },
                            "type": "object"
                          },
                          "type": "object"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Linked counts retrieved successfully",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Linked counts retrieved successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "example": {
                  "message": "Invalid UUID format: invalid-id-1, invalid-id-2...",
                  "success": false
                }
              }
            },
            "description": "Invalid UUID format in ids parameter"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get linked document counts for multiple transactions (batch)",
        "tags": [
          "Bank Statements"
        ]
      }
    },
    "/bank-statements/monthly-cash-flow": {
      "get": {
        "description": "Twelve (1–24) calendar months ending with the current month: deposits, withdrawals, transaction count and closing balance per month.\n\nClosing balance is the sum of each account's last known balance at month end, carried forward through quiet months and seeded from the last row before the window; a month before any balance is known reports null, never 0. Duplicates and soft-deleted rows are excluded. Tenant-scoped by the authenticated user.",
        "parameters": [
          {
            "description": "Window length in calendar months, ending with the current month",
            "in": "query",
            "name": "months",
            "required": false,
            "schema": {
              "default": 12,
              "maximum": 24,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "generatedAt": {
                          "format": "date-time",
                          "type": "string"
                        },
                        "months": {
                          "items": {
                            "properties": {
                              "closingBalance": {
                                "example": 49474000,
                                "nullable": true,
                                "type": "number"
                              },
                              "deposits": {
                                "example": 1250000,
                                "type": "number"
                              },
                              "financingNet": {
                                "description": "Deposits minus withdrawals of the rows whose 仕訳 books a 借入金 account (役員借入金 included): borrowing and repayment, so a 収支 can leave them out.",
                                "example": 2000000,
                                "type": "number"
                              },
                              "month": {
                                "description": "YYYY-MM",
                                "example": "2026-09",
                                "type": "string"
                              },
                              "transactionCount": {
                                "example": 42,
                                "type": "integer"
                              },
                              "withdrawals": {
                                "example": 830000,
                                "type": "number"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        },
                        "windowEnd": {
                          "description": "YYYYMMDD",
                          "example": 20260930,
                          "type": "integer"
                        },
                        "windowStart": {
                          "description": "YYYYMMDD",
                          "example": 20251001,
                          "type": "integer"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Monthly cash flow retrieved successfully",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Monthly cash flow retrieved successfully"
          },
          "400": {
            "description": "Invalid query (months must be 1–24)"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Monthly cash flow for the home chart (Console v3, ADR-0008)",
        "tags": [
          "Bank Statements"
        ]
      }
    },
    "/bank-statements/overview": {
      "get": {
        "description": "Returns a consolidated overview of all bank accounts, summary statistics, and sync status in a single API call.\n\n## Bank Statement Overview (銀行明細サマリー)\nDesigned for the bank statement landing page. Returns:\n- **accounts[]**: All bank accounts with latest balance, transaction count, connection status\n- **summary**: Total transactions, total balance, unassigned count, unreconciled count, date range\n- **syncStatus**: Bank API connection details (GMO Aozora, etc.)\n\nKeys are camelCase on the wire: the response middleware converts the service's snake_case.\n\nThis endpoint eliminates the need for multiple API calls to populate the bank statement page header and account selector.\n\n## Performance\nUses optimized aggregate queries with `LEFT JOIN LATERAL` for per-account latest balance. Single round-trip for all data.\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "empty": {
                    "summary": "No bank accounts configured",
                    "value": {
                      "data": {
                        "accounts": [],
                        "summary": {
                          "dateRange": {
                            "earliest": null,
                            "latest": null
                          },
                          "totalBalance": 0,
                          "totalTransactions": 0,
                          "unassignedCount": 0,
                          "unreconciledCount": 0
                        },
                        "syncStatus": {
                          "connections": []
                        }
                      },
                      "message": "Bank statement overview retrieved successfully",
                      "success": true
                    }
                  },
                  "with_accounts": {
                    "summary": "Overview with multiple accounts and API connection",
                    "value": {
                      "data": {
                        "accounts": [
                          {
                            "accountNumber": "1234567",
                            "accountType": "普通",
                            "bankName": "GMOあおぞらネット銀行",
                            "branchName": "法人営業部",
                            "connectionStatus": "connected",
                            "displayName": "メイン事業用口座",
                            "id": "789e0123-e45b-67c8-d901-234567890123",
                            "importSources": {
                              "csvImport": 6,
                              "manual": 150,
                              "paste": 0
                            },
                            "isPrimary": true,
                            "lastSyncAt": "2026-02-12T03:00:00.000Z",
                            "lastTransactionDate": 20260212,
                            "latestBalance": 1250000,
                            "latestSource": "api_gmo_aozora",
                            "purpose": "business",
                            "sortOrder": 0,
                            "transactionCount": 156
                          },
                          {
                            "accountNumber": "7654321",
                            "accountType": "普通",
                            "bankName": "三菱UFJ銀行",
                            "branchName": "渋谷支店",
                            "connectionStatus": null,
                            "displayName": "個人用口座",
                            "id": "aaa11111-bbbb-cccc-dddd-eeeeeeeeeeee",
                            "importSources": {
                              "csvImport": 42,
                              "manual": 0,
                              "paste": 3
                            },
                            "isPrimary": false,
                            "lastSyncAt": null,
                            "lastTransactionDate": 20260210,
                            "latestBalance": 850000,
                            "latestSource": "csv_import",
                            "purpose": "personal",
                            "sortOrder": 1,
                            "transactionCount": 42
                          }
                        ],
                        "summary": {
                          "dateRange": {
                            "earliest": 20240101,
                            "latest": 20260212
                          },
                          "totalBalance": 2100000,
                          "totalTransactions": 718,
                          "unassignedCount": 45,
                          "unreconciledCount": 120
                        },
                        "syncStatus": {
                          "connections": [
                            {
                              "id": "5c1d2e3f-4a5b-4c6d-8e7f-901234567890",
                              "lastSyncAt": "2026-02-12T03:00:00.000Z",
                              "lastSyncStatus": "success",
                              "provider": "gmo_aozora",
                              "status": "active"
                            }
                          ]
                        }
                      },
                      "message": "Bank statement overview retrieved successfully",
                      "success": true
                    }
                  }
                },
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/BankStatementOverview"
                    },
                    "message": {
                      "example": "Bank statement overview retrieved successfully",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Overview retrieved successfully (camelCase keys on the wire)"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get consolidated bank statement overview (v5.14+)",
        "tags": [
          "Bank Statements"
        ]
      }
    },
    "/bank-statements/reimbursement-summary": {
      "get": {
        "description": "Aggregated reimbursement summary with by-status breakdown and optional monthly grouping.",
        "operationId": "getReimbursementSummary",
        "parameters": [
          {
            "description": "YYYYMMDD format",
            "in": "query",
            "name": "start_date",
            "schema": {
              "type": "integer"
            }
          },
          {
            "description": "YYYYMMDD format",
            "in": "query",
            "name": "end_date",
            "schema": {
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "bank_account_id",
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Add monthly breakdown",
            "in": "query",
            "name": "group_by",
            "schema": {
              "enum": [
                "month"
              ],
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "byMonth": {
                          "description": "Present when group_by=month",
                          "items": {
                            "type": "object"
                          },
                          "type": "array"
                        },
                        "byStatus": {
                          "additionalProperties": {
                            "properties": {
                              "count": {
                                "type": "integer"
                              },
                              "totalAmount": {
                                "type": "integer"
                              }
                            },
                            "type": "object"
                          },
                          "description": "Count and total per status",
                          "type": "object"
                        },
                        "total": {
                          "properties": {
                            "count": {
                              "type": "integer"
                            },
                            "totalAmount": {
                              "type": "integer"
                            }
                          },
                          "type": "object"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Reimbursement summary"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "BearerAuth": []
          }
        ],
        "summary": "Get reimbursement summary (v5.15+)",
        "tags": [
          "Bank Statements"
        ]
      }
    },
    "/bank-statements/unjournalized-ids": {
      "get": {
        "description": "The ids behind the 未仕訳 badge — the rows 一括仕訳 would act on (BL-481).\n\nSame WHERE as `unjournalizedCount` on `GET /api/bank-statements`: live rows (is_duplicate = false,\ndeleted_at IS NULL) with no journal entry, narrowed by the SAME `bank_account_id` / `source` /\n`start_date`–`end_date` filters the list carries, so the badge, these ids and the visible rows describe\none slice. Paging and sorting params are rejected (400) — this endpoint always returns the newest first.\n\nAt most 1000 ids come back; `total` is the REAL count, so a caller can tell when a selection was clipped\nand narrow the period instead of acting on a partial set.",
        "operationId": "getUnjournalizedIds",
        "parameters": [
          {
            "example": 20260401,
            "in": "query",
            "name": "start_date",
            "required": false,
            "schema": {
              "type": "integer"
            }
          },
          {
            "example": 20270331,
            "in": "query",
            "name": "end_date",
            "required": false,
            "schema": {
              "type": "integer"
            }
          },
          {
            "description": "UUID, or the sentinel `unassigned` for transactions with no bank account.",
            "in": "query",
            "name": "bank_account_id",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "source",
            "required": false,
            "schema": {
              "enum": [
                "manual",
                "csv_import",
                "api_gmo_aozora",
                "paste"
              ],
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "ids": {
                          "items": {
                            "format": "uuid",
                            "type": "string"
                          },
                          "maxItems": 1000,
                          "type": "array"
                        },
                        "total": {
                          "description": "The uncapped count — greater than `ids.length` when the cap bit.",
                          "example": 12,
                          "type": "integer"
                        }
                      },
                      "required": [
                        "ids",
                        "total"
                      ],
                      "type": "object"
                    },
                    "message": {
                      "example": "Success",
                      "type": "string"
                    },
                    "requestId": {
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Unjournalized transaction ids (newest first, capped at 1000) and the real total"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "BearerAuth": []
          }
        ],
        "summary": "Ids of the transactions that still need a journal entry (v5.20+)",
        "tags": [
          "Bank Statements"
        ]
      }
    },
    "/bank-statements/unjournalized-preview": {
      "get": {
        "description": "Lightweight peek of unjournalized bank transactions for the GL inline panel.",
        "operationId": "getUnjournalizedPreview",
        "parameters": [
          {
            "in": "query",
            "name": "start_date",
            "schema": {
              "description": "YYYYMMDD",
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "end_date",
            "schema": {
              "description": "YYYYMMDD",
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "limit",
            "schema": {
              "default": 5,
              "maximum": 20,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "items": {
                          "items": {
                            "type": "object"
                          },
                          "type": "array"
                        },
                        "total": {
                          "type": "integer"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Preview total + items"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "BearerAuth": []
          }
        ],
        "summary": "Unjournalized transactions preview (v5.17+)",
        "tags": [
          "Bank Statements"
        ]
      }
    },
    "/bank-statements/{id}/details": {
      "get": {
        "description": "Get detailed transaction information including linked documents and derived processing status.\n\n## Transaction Details (取引明細詳細)\nComprehensive transaction details for the TransactionProcessingPanel:\n- **Document Links**: All documents linked via document_transaction_links\n- **Journal Entry**: Associated journal entry with line items\n- **Derived Status**: Frontend-friendly processing status\n\n## Processing Status (v4.29+)\nThe status system now supports both explicit and derived statuses:\n- **explicitStatus**: User-set status stored in database (null if not set)\n- **derivedStatus**: What status would be based on journal/document relationships\n- **processingStatus**: Effective status (explicit if set, otherwise derived)\n\n## Derived Processing Status Values\n- **unprocessed**: No journal entry, no linked documents\n- **journal_only**: Has journal entry, no linked documents\n- **doc_only**: No journal entry, has linked documents\n- **complete**: Has both journal entry AND linked documents\n- **no_doc_required**: User explicitly marked as not requiring documents (only via explicit set)\n\n## HTTP Caching (v4.34+ Production Enhancement)\nThis endpoint supports efficient HTTP caching:\n\n### Response Headers\n- `Cache-Control: private, max-age=60, stale-while-revalidate=30`\n- `ETag: \"{transactionId}-{updatedTimestamp}\"`\n- `Vary: Authorization`\n- `Last-Modified: {ISO timestamp}`\n\n### Conditional Requests (304 Not Modified)\nSend `If-None-Match` header with the cached ETag value:\n```\nGET /api/bank-statements/:id/details\nIf-None-Match: \"abc123-1705574400000\"\n```\nIf data hasn't changed, returns 304 with no body (saves bandwidth).\n\n### Frontend Integration\n```typescript\n// Store ETag from response\nconst etag = response.headers.get('ETag')\n\n// Send on subsequent requests\nfetch(url, { headers: { 'If-None-Match': etag } })\n// Returns 304 if unchanged\n```\n\n## Use Cases\n- **TransactionProcessingPanel**: Display transaction with all related data\n- **Status Badges**: Show accurate processing status\n- **Document Linking UI**: Show existing document links\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Bank transaction ID",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "ETag from previous response for conditional request (v4.34+)",
            "example": "\"abc123-1705574400000\"",
            "in": "header",
            "name": "If-None-Match",
            "required": false,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "complete_transaction": {
                    "summary": "Transaction with journal and document (complete)",
                    "value": {
                      "data": {
                        "derivedStatus": {
                          "hasJournalEntry": true,
                          "hasLinkedDocument": true,
                          "linkedDocumentCount": 1,
                          "processingStatus": "complete"
                        },
                        "documentLinks": [
                          {
                            "aiReasoning": "AWS料金として通信費に分類",
                            "document": {
                              "amount": 12800,
                              "id": "doc-111-222-333",
                              "name": "receipt_amazon_jan2026.pdf",
                              "status": "processed",
                              "type": "receipt",
                              "vendorName": "Amazon"
                            },
                            "documentId": "doc-111-222-333",
                            "documentType": "receipt",
                            "linkId": "abc12345-def6-7890-ghij-klmnopqrstuv",
                            "linkageType": "direct_expense",
                            "matchConfidence": 0.95,
                            "matchMethod": "ai_suggested"
                          }
                        ],
                        "journalEntry": {
                          "description": "Amazon購入",
                          "entryDate": 20260115,
                          "id": "456e7890-f12a-34b5-c678-901234567890",
                          "lines": [
                            {
                              "accountCode": "6230",
                              "accountName": "通信費",
                              "creditAmount": 0,
                              "debitAmount": 12800
                            },
                            {
                              "accountCode": "1100",
                              "accountName": "普通預金",
                              "creditAmount": 12800,
                              "debitAmount": 0
                            }
                          ],
                          "status": "posted"
                        },
                        "transaction": {
                          "balance": 1250000,
                          "bankAccount": {
                            "accountNumber": "1234567",
                            "bankName": "三菱UFJ銀行",
                            "branchName": "渋谷支店",
                            "id": "789e0123-e45b-67c8-d901-234567890123"
                          },
                          "depositAmount": 0,
                          "description": "アマゾン ジャパン",
                          "id": "123e4567-e89b-12d3-a456-426614174000",
                          "journalEntryId": "456e7890-f12a-34b5-c678-901234567890",
                          "memo": null,
                          "reconciliationStatus": "matched",
                          "transactionDate": 20260115,
                          "withdrawalAmount": 12800
                        }
                      },
                      "message": "Transaction details retrieved",
                      "statusCode": 200
                    }
                  },
                  "unprocessed_transaction": {
                    "summary": "Unprocessed transaction",
                    "value": {
                      "data": {
                        "derivedStatus": {
                          "hasJournalEntry": false,
                          "hasLinkedDocument": false,
                          "linkedDocumentCount": 0,
                          "processingStatus": "unprocessed"
                        },
                        "documentLinks": [],
                        "journalEntry": null,
                        "transaction": {
                          "balance": 1200000,
                          "depositAmount": 0,
                          "description": "ATM出金",
                          "id": "999e8888-f12a-34b5-c678-777666555444",
                          "journalEntryId": null,
                          "reconciliationStatus": "pending",
                          "transactionDate": 20260116,
                          "withdrawalAmount": 50000
                        }
                      },
                      "message": "Transaction details retrieved",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/TransactionDetailsResponse"
                }
              }
            },
            "description": "Transaction details retrieved successfully"
          },
          "304": {
            "description": "Not Modified - Data unchanged since last request (v4.34+)",
            "headers": {
              "Cache-Control": {
                "schema": {
                  "example": "private, no-cache",
                  "type": "string"
                }
              },
              "ETag": {
                "schema": {
                  "example": "\"abc123-1705574400000\"",
                  "type": "string"
                }
              },
              "Vary": {
                "schema": {
                  "example": "Authorization",
                  "type": "string"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "type": "null"
                    },
                    "message": {
                      "example": "Transaction not found",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 404,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Transaction not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get transaction details with document links and derived status",
        "tags": [
          "Bank Statements"
        ]
      }
    },
    "/bank-statements/{id}/link": {
      "post": {
        "description": "Link two transactions across bank accounts. Supports inter_account_transfer, reimbursement, and split link types.",
        "operationId": "createTransactionLink",
        "parameters": [
          {
            "description": "Source transaction ID",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "amount": {
                    "description": "Optional integer JPY amount (for partial links)",
                    "type": "integer"
                  },
                  "link_type": {
                    "enum": [
                      "inter_account_transfer",
                      "reimbursement",
                      "split"
                    ],
                    "type": "string"
                  },
                  "notes": {
                    "maxLength": 500,
                    "type": "string"
                  },
                  "target_transaction_id": {
                    "format": "uuid",
                    "type": "string"
                  }
                },
                "required": [
                  "target_transaction_id",
                  "link_type"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "amount": {
                          "nullable": true,
                          "type": "integer"
                        },
                        "created_at": {
                          "format": "date-time",
                          "type": "string"
                        },
                        "id": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "link_type": {
                          "type": "string"
                        },
                        "notes": {
                          "nullable": true,
                          "type": "string"
                        },
                        "source_transaction_id": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "target_transaction_id": {
                          "format": "uuid",
                          "type": "string"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Link created"
          },
          "400": {
            "description": "Self-reference (ERR_10024) or cross-user (ERR_10023)"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "409": {
            "description": "Duplicate link (ERR_10025)"
          }
        },
        "security": [
          {
            "BearerAuth": []
          }
        ],
        "summary": "Create transaction link (v5.15+)",
        "tags": [
          "Bank Statements"
        ]
      }
    },
    "/bank-statements/{id}/link-suggestions": {
      "get": {
        "description": "Returns rule-based link suggestions instantly. Add ?ai=true for AI-enhanced suggestions (~2-3s latency). Falls back to rule-based on AI failure.",
        "operationId": "getLinkSuggestions",
        "parameters": [
          {
            "description": "Source transaction ID",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Enable AI-enhanced suggestions (Tier 2)",
            "in": "query",
            "name": "ai",
            "schema": {
              "default": false,
              "type": "boolean"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "items": {
                        "properties": {
                          "confidence": {
                            "maximum": 1,
                            "minimum": 0,
                            "type": "number"
                          },
                          "isAiSuggestion": {
                            "description": "True if AI-enhanced",
                            "type": "boolean"
                          },
                          "matchReason": {
                            "description": "Japanese reason string",
                            "type": "string"
                          },
                          "suggestedLinkType": {
                            "enum": [
                              "inter_account_transfer",
                              "reimbursement",
                              "split"
                            ],
                            "type": "string"
                          },
                          "transactionId": {
                            "format": "uuid",
                            "type": "string"
                          }
                        },
                        "type": "object"
                      },
                      "type": "array"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Link suggestions"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Transaction not found"
          }
        },
        "security": [
          {
            "BearerAuth": []
          }
        ],
        "summary": "Get link suggestions (v5.15+)",
        "tags": [
          "Bank Statements"
        ]
      }
    },
    "/bank-statements/{id}/link/{target_id}": {
      "delete": {
        "description": "Remove a link between two transactions. If reimbursement link is deleted while source is \"paid\", auto-downgrades to \"approved\".",
        "operationId": "deleteTransactionLink",
        "parameters": [
          {
            "description": "Source transaction ID",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Target transaction ID",
            "in": "path",
            "name": "target_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "deleted": {
                          "type": "boolean"
                        },
                        "status_downgraded": {
                          "description": "True if reimbursement status was downgraded from paid to approved",
                          "type": "boolean"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Link deleted"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Link not found"
          }
        },
        "security": [
          {
            "BearerAuth": []
          }
        ],
        "summary": "Delete transaction link (v5.15+)",
        "tags": [
          "Bank Statements"
        ]
      }
    },
    "/bank-statements/{id}/memo": {
      "patch": {
        "description": "Update the user memo/notes for a bank transaction.",
        "operationId": "updateBankStatementMemo",
        "parameters": [
          {
            "description": "Bank statement ID",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "memo": {
                    "description": "User memo or notes",
                    "maxLength": 500,
                    "nullable": true,
                    "type": "string"
                  }
                },
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "id": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "memo": {
                          "nullable": true,
                          "type": "string"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Memo updated"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Transaction not found"
          }
        },
        "security": [
          {
            "BearerAuth": []
          }
        ],
        "summary": "Update transaction memo",
        "tags": [
          "Bank Statements"
        ]
      }
    },
    "/bank-statements/{id}/processing-status": {
      "patch": {
        "description": "Update the processing status for a bank transaction. This allows explicitly setting a status that persists to the database.\n\n## Processing Status Update (処理ステータス更新)\nPersist user-specified processing status that:\n- **Survives Page Refresh**: Status is stored in database, not just frontend state\n- **Overrides Derived Status**: Explicit status takes precedence over automatic derivation\n- **Can Be Cleared**: Set to null to revert to derived behavior\n\n## Status Values\n| Status | Description |\n|--------|-------------|\n| `unprocessed` | No journal entry, no linked documents |\n| `journal_only` | Has journal entry, no linked documents |\n| `doc_only` | No journal entry, has linked documents |\n| `complete` | Has both journal entry AND linked documents |\n| `no_doc_required` | User explicitly marked as not requiring documents |\n| `null` | Clear explicit status, revert to derived behavior |\n\n## Use Cases\n- **Mark No Doc Required**: When a transaction legitimately doesn't need a document (e.g., bank fees, internal transfers)\n- **Override Status**: Temporarily override the derived status for special cases\n- **Clear Override**: Set to null to resume automatic status derivation\n\n## Status Logic\n- If `processing_status` is set (non-null): Use this explicit status\n- If `processing_status` is null: Derive from journal/document relationships\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Bank transaction ID",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "clear_explicit_status": {
                  "description": "Revert to automatic derivation based on journal/document relationships",
                  "summary": "Clear explicit status",
                  "value": {
                    "processing_status": null
                  }
                },
                "mark_complete": {
                  "description": "Explicitly mark as complete even if automatic derivation would differ",
                  "summary": "Mark as complete",
                  "value": {
                    "processing_status": "complete"
                  }
                },
                "mark_no_doc_required": {
                  "description": "Use when a document is not needed for this transaction",
                  "summary": "Mark as no document required",
                  "value": {
                    "processing_status": "no_doc_required"
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/UpdateProcessingStatusRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "cleared_status": {
                    "summary": "Status cleared, reverted to derived",
                    "value": {
                      "data": {
                        "derivedStatus": "journal_only",
                        "documentCount": 0,
                        "effectiveStatus": "journal_only",
                        "hasJournal": true,
                        "isExplicit": false,
                        "processingStatus": null,
                        "transactionId": "123e4567-e89b-12d3-a456-426614174000"
                      },
                      "message": "Processing status updated successfully",
                      "statusCode": 200
                    }
                  },
                  "explicit_status": {
                    "summary": "Status explicitly set",
                    "value": {
                      "data": {
                        "derivedStatus": "unprocessed",
                        "documentCount": 0,
                        "effectiveStatus": "no_doc_required",
                        "hasJournal": false,
                        "isExplicit": true,
                        "processingStatus": "no_doc_required",
                        "transactionId": "123e4567-e89b-12d3-a456-426614174000"
                      },
                      "message": "Processing status updated successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/UpdateProcessingStatusResponse"
                }
              }
            },
            "description": "Processing status updated successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "example": {
                  "message": "processing_status must be one of: unprocessed, journal_only, doc_only, complete, no_doc_required, or null to clear",
                  "statusCode": 400
                }
              }
            },
            "description": "Invalid processing status value"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "example": {
                  "data": null,
                  "message": "Transaction not found",
                  "statusCode": 404
                }
              }
            },
            "description": "Transaction not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update processing status for a bank transaction (v4.29+)",
        "tags": [
          "Bank Statements"
        ]
      }
    },
    "/bank-statements/{id}/reimbursement": {
      "patch": {
        "description": "Update reimbursement flag, status, and notes for a bank transaction. Enforces state machine transitions.",
        "operationId": "updateBankStatementReimbursement",
        "parameters": [
          {
            "description": "Bank statement ID",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "is_reimbursable": {
                    "description": "Flag transaction as reimbursable",
                    "type": "boolean"
                  },
                  "reimbursement_notes": {
                    "description": "Optional notes",
                    "maxLength": 2000,
                    "type": "string"
                  },
                  "reimbursement_status": {
                    "description": "New reimbursement status (state machine enforced)",
                    "enum": [
                      "pending",
                      "submitted",
                      "approved",
                      "paid",
                      "rejected",
                      "cancelled"
                    ],
                    "type": "string"
                  }
                },
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "id": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "is_reimbursable": {
                          "type": "boolean"
                        },
                        "reimbursement_notes": {
                          "nullable": true,
                          "type": "string"
                        },
                        "reimbursement_status": {
                          "type": "string"
                        },
                        "reimbursement_status_changed_at": {
                          "format": "date-time",
                          "nullable": true,
                          "type": "string"
                        },
                        "reimbursement_status_changed_by": {
                          "format": "uuid",
                          "nullable": true,
                          "type": "string"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Reimbursement status updated"
          },
          "400": {
            "description": "Invalid transition (ERR_10026) or non-personal account (ERR_10027)"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Transaction not found"
          }
        },
        "security": [
          {
            "BearerAuth": []
          }
        ],
        "summary": "Update reimbursement status (v5.15+)",
        "tags": [
          "Bank Statements"
        ]
      }
    },
    "/bulk-upload/connect": {
      "get": {
        "description": "Establish a Server-Sent Events connection for real-time bulk upload progress tracking.\n\n## SSE Connection\nCreates persistent connection for real-time updates:\n- **Event Stream**: Continuous progress updates during file processing\n- **Session Tracking**: Progress updates specific to session ID\n- **Real-time Data**: Processing status, completion percentage, error notifications\n- **Connection Management**: Automatic cleanup and reconnection handling\n\n## Query Parameters\n- **sessionId**: Required session identifier for progress tracking\n- **clientId**: Optional client identifier for connection management\n\n## Event Types\n- **progress**: File processing progress updates\n- **completed**: Individual file completion notifications\n- **error**: Error notifications for failed operations\n- **session-complete**: All files in session processed\n\n## Authentication\n- **Optional**: Uses optional SSE auth middleware\n- **Token-based**: Bearer token in Authorization header (when available)\n- **Anonymous**: Supports unauthenticated progress tracking\n\n## Connection Management\n- **Keep-alive**: Maintains persistent connection\n- **Cleanup**: Automatic cleanup on client disconnect\n- **Reconnection**: Client-side reconnection support\n- **Timeout**: Connection timeout handling\n\n## Use Cases\n- Real-time progress bars in web interfaces\n- Live status updates during bulk operations\n- Error notification and handling\n- Session completion tracking\n\n## Browser Compatibility\n- **EventSource API**: Standard browser SSE support\n- **CORS**: Cross-origin request support\n- **Reconnection**: Automatic reconnection on connection loss",
        "parameters": [
          {
            "description": "Session identifier for progress tracking",
            "example": "session_1705312200000_abc123def",
            "in": "query",
            "name": "sessionId",
            "required": true,
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "Optional client identifier",
            "example": "client_browser_001",
            "in": "query",
            "name": "clientId",
            "required": false,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "text/event-stream": {
                "schema": {
                  "example": "data: {\"type\":\"progress\",\"sessionId\":\"session_123\",\"progress\":45,\"message\":\"Processing file 3 of 5\"}\n\n",
                  "type": "string"
                }
              }
            },
            "description": "SSE connection established"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Session ID is required for SSE connection",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Missing or invalid session ID"
          }
        },
        "summary": "Establish SSE connection for real-time progress",
        "tags": [
          "Bulk Upload"
        ]
      },
      "options": {
        "description": "Handle CORS preflight requests for Server-Sent Events connections.\n\n## CORS Configuration\nEnables cross-origin requests for real-time progress tracking:\n- **Origin**: Wildcard (*) for development flexibility\n- **Methods**: GET, POST, OPTIONS for SSE and upload operations\n- **Headers**: Content-Type and Authorization for authenticated requests\n\n## Use Cases\n- Browser preflight requests before establishing SSE connections\n- Cross-origin web application integration\n- Development environment CORS handling\n- Client-side real-time progress tracking setup\n\n## Implementation Notes\n- No authentication required for preflight requests\n- Standard CORS headers for SSE compatibility\n- Supports both authenticated and anonymous connections",
        "responses": {
          "200": {
            "description": "CORS preflight successful",
            "headers": {
              "Access-Control-Allow-Headers": {
                "description": "Allowed request headers",
                "schema": {
                  "example": "Content-Type, Authorization",
                  "type": "string"
                }
              },
              "Access-Control-Allow-Methods": {
                "description": "Allowed HTTP methods",
                "schema": {
                  "example": "GET, POST, OPTIONS",
                  "type": "string"
                }
              },
              "Access-Control-Allow-Origin": {
                "description": "Allowed origins for CORS",
                "schema": {
                  "example": "*",
                  "type": "string"
                }
              }
            }
          }
        },
        "summary": "CORS preflight for SSE connection",
        "tags": [
          "Bulk Upload"
        ]
      }
    },
    "/bulk-upload/queue/status": {
      "get": {
        "description": "Retrieve current status of the file processing queue with job statistics.\n\n## Queue Information\nReturns comprehensive queue statistics:\n- **Total Jobs**: All jobs currently in the system\n- **Pending Jobs**: Jobs waiting to be processed\n- **Processing Jobs**: Jobs currently being processed\n- **Completed Jobs**: Successfully completed jobs\n- **Failed Jobs**: Jobs that encountered errors\n\n## Use Cases\n- **System Monitoring**: Track overall system load and performance\n- **Capacity Planning**: Understand processing capacity and bottlenecks\n- **Health Checks**: Monitor system health and processing efficiency\n- **User Interface**: Display queue status in admin dashboards\n\n## Real-time Updates\n- **Current State**: Snapshot of queue at request time\n- **Dynamic Data**: Updates as jobs are processed\n- **Performance Metrics**: Processing throughput and efficiency\n- **Load Balancing**: Information for scaling decisions\n\n## No Authentication Required\nPublic endpoint for system status monitoring.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/QueueStatusResponse"
                }
              }
            },
            "description": "Queue status retrieved successfully"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "Get processing queue status",
        "tags": [
          "Bulk Upload"
        ]
      }
    },
    "/bulk-upload/reprocess/{sessionId}": {
      "post": {
        "description": "Queue one file of an upload session for a new AI read: a file that failed, or a restored\nfile (作業の復元) whose stored read came from an older extraction prompt.\n\nEvery call is a fresh LLM read with the current prompt. This path never consults the\n`document_parse_results` cache, so there is no bypass flag here (contrast\n`POST /file-uploads/{file_id}/analyze` with `bypass_parse_cache`).\n\nThe job is linked to the session's `session_files` row by `original_name`, so the new read\nreplaces the stored `ai_data` and reaches the modal through the session record (the\n`/session/{sessionId}/jobs` poll and the SSE bridge). Progress is pushed as\n`file_reprocessing_started` / `file_reprocessing_completed` / `file_reprocessing_failed`.\n\nMultipart text fields may be sent camelCase (`fileName`, `originalName`, `mimeType`); they are\nconverted after multer. Any other field is a 400.",
        "parameters": [
          {
            "description": "Upload session the file belongs to (owner-checked)",
            "example": "session_1705312200000_abc123def",
            "in": "path",
            "name": "sessionId",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "multipart/form-data": {
              "schema": {
                "additionalProperties": false,
                "properties": {
                  "file": {
                    "description": "The file bytes (JPEG, PNG, PDF or DOCX)",
                    "format": "binary",
                    "type": "string"
                  },
                  "file_name": {
                    "example": "20261015 納付書.pdf",
                    "maxLength": 512,
                    "type": "string"
                  },
                  "mime_type": {
                    "example": "application/pdf",
                    "maxLength": 128,
                    "type": "string"
                  },
                  "original_name": {
                    "description": "Name the session stored the file under; links the job to its session_files row",
                    "example": "20261015 納付書.pdf",
                    "maxLength": 512,
                    "type": "string"
                  }
                },
                "required": [
                  "file",
                  "file_name",
                  "original_name",
                  "mime_type"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "sessionId": {
                          "example": "session_1705312200000_abc123def",
                          "type": "string"
                        }
                      },
                      "required": [
                        "sessionId"
                      ],
                      "type": "object"
                    },
                    "message": {
                      "example": "File 20261015 納付書.pdf queued for re-processing",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "message",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Queued for a new read"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Read one session file again",
        "tags": [
          "Bulk Upload"
        ]
      }
    },
    "/bulk-upload/reupload/{sessionId}": {
      "post": {
        "description": "Re-runs the save of one confirmed file of an upload session (再アップロード): stores the file,\ncreates its `file_uploads` row with `ai_data` / `confirmed_data`, and — when `confirmed_data` has\ncontent — the expense. Progress is pushed as `file_reupload_started` and the upload events.\n\nMultipart text fields may be sent camelCase (`originalFileName`, `confirmedFileName`, `mimeType`,\n`aiData`, `confirmedData`, `sessionId`); they are converted after multer. Any other field is a 400.\n\n`ai_data` and `confirmed_data` are JSON objects in a form field. `confirmed_data` types the keys the\nexpense is written from (below); other keys are kept and stored as sent. Keys inside stay camelCase.\n`session_id`, when sent, must equal the path's session (400 otherwise).",
        "parameters": [
          {
            "description": "Upload session the file belongs to",
            "example": "session_1705312200000_abc123def",
            "in": "path",
            "name": "sessionId",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "multipart/form-data": {
              "schema": {
                "additionalProperties": false,
                "properties": {
                  "ai_data": {
                    "contentMediaType": "application/json",
                    "description": "JSON object: the AI read, stored as file_uploads.ai_data",
                    "type": "string"
                  },
                  "confirmed_data": {
                    "contentMediaType": "application/json",
                    "description": "JSON object: the confirmed read. Typed keys (all optional, nullable): date, payee, currency, invoiceNumber, orderNumber, payeeRegistrationNumber, businessPurpose (string); amount, taxAmount, originalAmount (number); category, taxType, paymentMethod (integer or string code); remarks (string or string[]). Other keys are stored as sent.",
                    "type": "string"
                  },
                  "confirmed_file_name": {
                    "example": "20261015_JPY465600_東京都主税局.PDF",
                    "maxLength": 512,
                    "type": "string"
                  },
                  "file": {
                    "description": "The file bytes",
                    "format": "binary",
                    "type": "string"
                  },
                  "mime_type": {
                    "example": "application/pdf",
                    "maxLength": 128,
                    "type": "string"
                  },
                  "original_file_name": {
                    "example": "20261015 納付書.pdf",
                    "maxLength": 512,
                    "type": "string"
                  },
                  "session_id": {
                    "description": "Optional; must equal the path session",
                    "maxLength": 255,
                    "type": "string"
                  }
                },
                "required": [
                  "file",
                  "original_file_name",
                  "confirmed_file_name",
                  "mime_type"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "message": {
                      "example": "File 20261015 納付書.pdf queued for re-upload",
                      "type": "string"
                    },
                    "sessionId": {
                      "example": "session_1705312200000_abc123def",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "message",
                    "sessionId"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Queued for saving"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Save one session file again after its save failed",
        "tags": [
          "Bulk Upload"
        ]
      }
    },
    "/bulk-upload/session/{sessionId}/jobs": {
      "delete": {
        "description": "Clear all processing jobs for a specific session, removing job data and freeing resources.\n\n## Cleanup Operations\nPerforms comprehensive session cleanup:\n- **Job Removal**: Delete all jobs associated with session\n- **Memory Cleanup**: Free allocated memory and resources\n- **Progress Reset**: Clear session progress tracking data\n- **File Cleanup**: Remove temporary files and processing data\n\n## Use Cases\n- **Session Reset**: Clear session for reprocessing\n- **Resource Management**: Free system resources after completion\n- **Error Recovery**: Clean up after failed processing sessions\n- **Storage Optimization**: Remove unnecessary temporary data\n\n## Cleanup Scope\n- **Processing Jobs**: All AI processing job data\n- **Temporary Files**: Cached file data and processing results\n- **Progress Data**: Session progress and status information\n- **Error Logs**: Session-specific error and diagnostic data\n\n## No Authentication Required\nPublic endpoint for session cleanup (session ID provides access control).",
        "parameters": [
          {
            "description": "Session identifier for job cleanup",
            "example": "session_1705312200000_abc123def",
            "in": "path",
            "name": "sessionId",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "clearedJobs": {
                          "example": 5,
                          "type": "integer"
                        },
                        "sessionId": {
                          "example": "session_1705312200000_abc123def",
                          "type": "string"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Session jobs cleared successfully",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Session jobs cleared successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Session ID is required",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid or missing session ID"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "Clear session processing jobs",
        "tags": [
          "Bulk Upload"
        ]
      },
      "get": {
        "description": "Retrieve all processing jobs for a specific session with detailed job information.\n\n## Job Information\nReturns array of processing jobs with:\n- **Job Details**: ID, file names, processing status\n- **Processing Results**: AI analysis results and suggested names\n- **Error Information**: Detailed error messages for failed jobs\n- **Timestamps**: Creation and completion times\n- **File Metadata**: Original names, MIME types, and processing data\n\n## Job Status Types\n- **Pending**: Job queued for processing\n- **Processing**: Currently being processed by AI\n- **Completed**: Successfully processed with results\n- **Failed**: Processing failed with error details\n\n## Use Cases\n- **Job Monitoring**: Track individual file processing status\n- **Result Retrieval**: Access AI processing results\n- **Error Diagnosis**: Investigate failed processing jobs\n- **Progress Display**: Show detailed progress per file\n\n## No Authentication Required\nPublic endpoint for job tracking (session ID provides access control).",
        "parameters": [
          {
            "description": "Session identifier for job retrieval",
            "example": "session_1705312200000_abc123def",
            "in": "path",
            "name": "sessionId",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SessionJobsResponse"
                }
              }
            },
            "description": "Session jobs retrieved successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Session ID is required",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid or missing session ID"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Session not found",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Session not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "Get session processing jobs",
        "tags": [
          "Bulk Upload"
        ]
      }
    },
    "/bulk-upload/session/{sessionId}/progress": {
      "get": {
        "description": "Retrieve detailed progress information for a specific upload session.\n\n## Progress Tracking\nReturns comprehensive session progress data:\n- **File Counts**: Total, processed, completed, and failed file counts\n- **Progress Percentage**: Overall session completion percentage\n- **Status Information**: Current processing state and completion status\n- **Error Tracking**: Failed file information and error details\n\n## Session Management\n- **Session Lifecycle**: Track progress from start to completion\n- **Real-time Updates**: Current state at time of request\n- **Historical Data**: Completed session information retention\n- **Error Recovery**: Information for handling failed files\n\n## Use Cases\n- **Progress Bars**: Display upload and processing progress\n- **Status Dashboards**: Monitor multiple session progress\n- **Error Handling**: Identify and handle failed operations\n- **Completion Tracking**: Determine when sessions are complete\n\n## No Authentication Required\nPublic endpoint for progress tracking (session ID provides access control).",
        "parameters": [
          {
            "description": "Session identifier for progress tracking",
            "example": "session_1705312200000_abc123def",
            "in": "path",
            "name": "sessionId",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SessionProgressResponse"
                }
              }
            },
            "description": "Session progress retrieved successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Session ID is required",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid or missing session ID"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Session not found",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Session not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "Get session progress information",
        "tags": [
          "Bulk Upload"
        ]
      }
    },
    "/bulk-upload/stats": {
      "get": {
        "description": "Retrieve comprehensive system statistics including queue status, connected clients, and system health metrics.\n\n## System Metrics\nReturns detailed system information:\n- **Queue Statistics**: Current queue status and job counts\n- **Client Connections**: Number of active SSE connections\n- **System Health**: Memory usage, CPU usage, and uptime metrics\n- **Performance Data**: Processing throughput and efficiency metrics\n\n## Monitoring Data\n- **Real-time Status**: Current system state and performance\n- **Resource Usage**: Memory and CPU utilization\n- **Connection Management**: Active client connection tracking\n- **Processing Metrics**: Job processing rates and success ratios\n\n## Use Cases\n- **System Monitoring**: Track overall system health and performance\n- **Capacity Planning**: Monitor resource usage for scaling decisions\n- **Performance Optimization**: Identify bottlenecks and optimization opportunities\n- **Health Dashboards**: Display system status in monitoring interfaces\n\n## Administrative Information\n- **Load Balancing**: Data for traffic distribution decisions\n- **Scaling Metrics**: Information for auto-scaling configurations\n- **Alert Thresholds**: Data for system alerting and monitoring\n- **Diagnostic Data**: Information for troubleshooting and optimization\n\n## No Authentication Required\nPublic endpoint for system monitoring and health checks.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SystemStatsResponse"
                }
              }
            },
            "description": "System statistics retrieved successfully"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "Get system statistics",
        "tags": [
          "Bulk Upload"
        ]
      }
    },
    "/bulk-upload/upload": {
      "post": {
        "description": "Upload multiple files for bulk processing with AI analysis and real-time progress tracking.\n\n## File Upload Specifications\n- **Maximum Files**: 20 files per batch\n- **File Size Limit**: 5 MB (5,242,880 bytes) per individual file — 413 `FILE_SIZE_EXCEEDED` above it, with a Japanese message naming the limit and the request size\n- **Request Size Limit**: the whole multipart request must stay under 6,291,456 bytes (AWS Lambda's synchronous invocation cap; the Function URL refuses larger requests before the API sees them). Split a batch whose files sum to more than that. Source of truth: `src/common/constants/upload-limits.ts` (`UPLOAD_LIMITS`), mirrored by the FE modal.\n- **Supported Types**: JPEG, PNG, PDF, DOCX (validated by magic bytes)\n- **Validation**: Content-based validation prevents MIME type spoofing\n- **Processing**: AI-powered content analysis and data extraction\n\n## Supported File Types\n- **Images**: JPEG, PNG for receipt and document scanning\n- **Documents**: PDF, DOCX for text extraction and analysis\n- **Validation**: Magic byte validation ensures file integrity\n- **Security**: Protection against malicious file uploads\n\n## AI Processing Features\n- **Text Extraction**: OCR for images and document text extraction\n- **Content Analysis**: AI-powered categorization and data extraction\n- **Suggested Naming**: Intelligent file naming based on content\n- **Data Structuring**: Extraction of structured data (amounts, dates, vendors)\n\n## Session Management\n- **Session ID**: Auto-generated or provided session identifier\n- **Progress Tracking**: Real-time updates via SSE connection\n- **Job Queuing**: Asynchronous processing with queue management\n- **Error Handling**: Individual file error tracking and reporting\n\n## Request Format\n- **Content-Type**: multipart/form-data for file uploads\n- **Files Field**: 'files' array containing uploaded files\n- **Session ID**: Optional sessionId in request body\n- **Metadata**: Additional processing parameters\n\n## Response Data\n- **Session Information**: Generated session ID for tracking\n- **Queue Status**: Number of queued jobs for processing\n- **Progress Tracking**: Instructions for SSE connection setup\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "multipart/form-data": {
              "schema": {
                "properties": {
                  "files": {
                    "description": "Array of files to upload (max 20 files, 5 MB each, whole request under 6,291,456 bytes)",
                    "items": {
                      "format": "binary",
                      "type": "string"
                    },
                    "maxItems": 20,
                    "type": "array"
                  },
                  "sessionId": {
                    "description": "Optional session ID (auto-generated if not provided)",
                    "example": "session_1705312200000_abc123def",
                    "type": "string"
                  }
                },
                "required": [
                  "files"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BulkUploadResponse"
                }
              }
            },
            "description": "Bulk upload started successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "details": {
                      "items": {
                        "properties": {
                          "error": {
                            "example": "Unsupported file type",
                            "type": "string"
                          },
                          "fileName": {
                            "example": "document.txt",
                            "type": "string"
                          }
                        },
                        "type": "object"
                      },
                      "type": "array"
                    },
                    "error": {
                      "example": "Invalid file type or size limit exceeded",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid files or validation errors"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "413": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "File size limit exceeded (2MB max per file)",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "File size or count limit exceeded"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Bulk file upload with AI processing",
        "tags": [
          "Bulk Upload"
        ]
      }
    },
    "/changelog": {
      "get": {
        "description": "Retrieves the complete changelog with version history, categorized commits, and statistics.\n      \n## Changelog Generation\n- **Git History Parsing**: Analyzes git commit history using conventional commit format\n- **Version Grouping**: Groups commits by version tags and releases\n- **Categorization**: Organizes commits by type (features, fixes, docs, etc.)\n- **Statistics**: Provides metrics on commits, versions, and update history\n\n## Conventional Commit Support\n- **feat**: New features (minor version bump)\n- **fix**: Bug fixes (patch version bump)\n- **docs**: Documentation changes\n- **perf**: Performance improvements\n- **refactor**: Code refactoring\n- **chore**: Maintenance tasks\n- **BREAKING CHANGE**: Major changes (major version bump)\n\n## Version Management\n- **Semantic Versioning**: Follows semver principles for version numbering\n- **Tag Integration**: Uses git tags to identify version boundaries\n- **Release Categorization**: Tags versions as latest, stable, beta, or alpha\n- **Change Tracking**: Tracks all changes between versions\n\n## Use Cases\n- **Release Notes**: Generate release notes for new versions\n- **Change Documentation**: Document all changes for users and developers\n- **Version Planning**: Understand what changes are included in versions\n- **Development History**: Track project evolution over time",
        "parameters": [
          {
            "description": "Maximum number of commits to include",
            "in": "query",
            "name": "limit",
            "required": false,
            "schema": {
              "default": 50,
              "maximum": 1000,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-changelog": {
                    "summary": "Successful changelog retrieval",
                    "value": {
                      "data": {
                        "stats": {
                          "lastUpdated": "2024-01-15T10:30:00.000Z",
                          "totalCommits": 150,
                          "totalVersions": 5
                        },
                        "versions": [
                          {
                            "changes": {
                              "breaking": [],
                              "chore": [],
                              "docs": [],
                              "features": [
                                {
                                  "author": "John Doe",
                                  "date": "2024-01-15T10:30:00.000Z",
                                  "hash": "a1b2c3d4e5f6789012345678901234567890abcd",
                                  "isBreaking": false,
                                  "message": "feat(auth): add OAuth2 integration",
                                  "scope": "auth",
                                  "shortHash": "a1b2c3d",
                                  "subject": "add OAuth2 integration",
                                  "type": "feat"
                                }
                              ],
                              "fixes": [
                                {
                                  "author": "Jane Smith",
                                  "date": "2024-01-14T15:20:00.000Z",
                                  "hash": "b2c3d4e5f6789012345678901234567890abcde1",
                                  "isBreaking": false,
                                  "message": "fix(api): resolve authentication timeout",
                                  "scope": "api",
                                  "shortHash": "b2c3d4e",
                                  "subject": "resolve authentication timeout",
                                  "type": "fix"
                                }
                              ],
                              "other": [],
                              "perf": [],
                              "refactor": []
                            },
                            "date": "2024-01-15",
                            "tag": "latest",
                            "version": "v1.2.3"
                          }
                        ]
                      },
                      "message": "Changelog retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ChangelogResponse"
                }
              }
            },
            "description": "Changelog retrieved successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "examples": {
                  "invalid-limit": {
                    "summary": "Invalid limit parameter",
                    "value": {
                      "error": "Bad Request",
                      "message": "Limit parameter must be between 1 and 1000",
                      "statusCode": 400
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Invalid query parameters"
          },
          "500": {
            "content": {
              "application/json": {
                "examples": {
                  "git-error": {
                    "summary": "Git repository error",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "Failed to read git history",
                      "statusCode": 500
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error"
          }
        },
        "summary": "Get complete changelog with version history",
        "tags": [
          "Changelog"
        ]
      }
    },
    "/changelog/commits": {
      "get": {
        "description": "Retrieves git commits with parsed conventional commit information.\n      \n## Git Commit Information\n- **Full History**: Complete git commit history with metadata\n- **Conventional Parsing**: Parses conventional commit format\n- **Author Information**: Commit author and timestamp details\n- **Breaking Change Detection**: Identifies breaking changes\n\n## Commit Metadata\n- **Hash Information**: Full and short commit hashes\n- **Timestamps**: ISO format commit dates\n- **Author Details**: Commit author names\n- **Message Parsing**: Type, scope, subject, and body extraction\n\n## Conventional Commit Format\n- **Type**: Commit type (feat, fix, docs, etc.)\n- **Scope**: Optional scope in parentheses\n- **Subject**: Brief description of changes\n- **Body**: Optional detailed description\n- **Breaking**: Detection of breaking changes\n\n## Use Cases\n- **Development History**: Complete view of project development\n- **Commit Analysis**: Analyze commit patterns and types\n- **Author Statistics**: Track contributor activity\n- **Change Tracking**: Detailed change history for auditing",
        "parameters": [
          {
            "description": "Maximum number of commits to retrieve",
            "in": "query",
            "name": "limit",
            "required": false,
            "schema": {
              "default": 100,
              "maximum": 1000,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-commits": {
                    "summary": "Successful git commits retrieval",
                    "value": {
                      "data": [
                        {
                          "author": "John Doe",
                          "date": "2024-01-15T10:30:00.000Z",
                          "hash": "a1b2c3d4e5f6789012345678901234567890abcd",
                          "isBreaking": false,
                          "message": "feat(auth): add OAuth2 integration",
                          "scope": "auth",
                          "shortHash": "a1b2c3d",
                          "subject": "add OAuth2 integration",
                          "type": "feat"
                        },
                        {
                          "author": "Jane Smith",
                          "date": "2024-01-14T15:20:00.000Z",
                          "hash": "b2c3d4e5f6789012345678901234567890abcde1",
                          "isBreaking": false,
                          "message": "fix(api): resolve authentication timeout",
                          "scope": "api",
                          "shortHash": "b2c3d4e",
                          "subject": "resolve authentication timeout",
                          "type": "fix"
                        },
                        {
                          "author": "Bob Johnson",
                          "date": "2024-01-13T09:15:00.000Z",
                          "hash": "c3d4e5f6789012345678901234567890abcde12f",
                          "isBreaking": false,
                          "message": "docs(api): update authentication guide",
                          "scope": "api",
                          "shortHash": "c3d4e5f",
                          "subject": "update authentication guide",
                          "type": "docs"
                        }
                      ],
                      "message": "Git commits retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/CommitsResponse"
                }
              }
            },
            "description": "Git commits retrieved successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "examples": {
                  "invalid-limit": {
                    "summary": "Invalid limit parameter",
                    "value": {
                      "error": "Bad Request",
                      "message": "Limit parameter must be between 1 and 1000",
                      "statusCode": 400
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Invalid query parameters"
          },
          "500": {
            "content": {
              "application/json": {
                "examples": {
                  "git-error": {
                    "summary": "Git repository error",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "Failed to retrieve git commits",
                      "statusCode": 500
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error"
          }
        },
        "summary": "Get git commits with conventional commit parsing",
        "tags": [
          "Changelog"
        ]
      }
    },
    "/changelog/recent": {
      "get": {
        "description": "Retrieves recent changes categorized by commit type for quick overview of latest developments.\n      \n## Recent Changes Overview\n- **Features**: Latest feature additions and enhancements\n- **Fixes**: Recent bug fixes and patches\n- **Documentation**: Recent documentation updates\n- **Other**: Other types of changes (style, test, chore)\n\n## Categorization Logic\n- **Features**: feat, feature commits\n- **Fixes**: fix, bug commits\n- **Documentation**: docs, doc, documentation commits\n- **Other**: All other commit types not in main categories\n\n## Use Cases\n- **Dashboard Widgets**: Show recent activity in application dashboards\n- **Quick Updates**: Provide quick overview of recent changes\n- **Development Status**: Show current development activity\n- **Change Notifications**: Inform users about recent improvements",
        "parameters": [
          {
            "description": "Maximum number of recent commits to analyze",
            "in": "query",
            "name": "limit",
            "required": false,
            "schema": {
              "default": 20,
              "maximum": 100,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-recent-changes": {
                    "summary": "Successful recent changes retrieval",
                    "value": {
                      "data": {
                        "docs": [
                          {
                            "author": "Bob Johnson",
                            "date": "2024-01-13T09:15:00.000Z",
                            "hash": "c3d4e5f6789012345678901234567890abcde12f",
                            "isBreaking": false,
                            "message": "docs(api): update authentication guide",
                            "scope": "api",
                            "shortHash": "c3d4e5f",
                            "subject": "update authentication guide",
                            "type": "docs"
                          }
                        ],
                        "features": [
                          {
                            "author": "John Doe",
                            "date": "2024-01-15T10:30:00.000Z",
                            "hash": "a1b2c3d4e5f6789012345678901234567890abcd",
                            "isBreaking": false,
                            "message": "feat(auth): add OAuth2 integration",
                            "scope": "auth",
                            "shortHash": "a1b2c3d",
                            "subject": "add OAuth2 integration",
                            "type": "feat"
                          }
                        ],
                        "fixes": [
                          {
                            "author": "Jane Smith",
                            "date": "2024-01-14T15:20:00.000Z",
                            "hash": "b2c3d4e5f6789012345678901234567890abcde1",
                            "isBreaking": false,
                            "message": "fix(api): resolve authentication timeout",
                            "scope": "api",
                            "shortHash": "b2c3d4e",
                            "subject": "resolve authentication timeout",
                            "type": "fix"
                          }
                        ],
                        "other": []
                      },
                      "message": "Recent changes retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/RecentChangesResponse"
                }
              }
            },
            "description": "Recent changes retrieved successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "examples": {
                  "invalid-limit": {
                    "summary": "Invalid limit parameter",
                    "value": {
                      "error": "Bad Request",
                      "message": "Limit parameter must be between 1 and 100",
                      "statusCode": 400
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Invalid query parameters"
          },
          "500": {
            "content": {
              "application/json": {
                "examples": {
                  "git-error": {
                    "summary": "Git repository error",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "Failed to read recent git commits",
                      "statusCode": 500
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error"
          }
        },
        "summary": "Get recent changes categorized by type",
        "tags": [
          "Changelog"
        ]
      }
    },
    "/changelog/version": {
      "get": {
        "description": "Retrieves current version information, recent commits, and recommended version bump.\n      \n## Version Information\n- **Current Version**: Version from package.json\n- **Recent Commits**: Latest commits since last version\n- **Recommended Bump**: Suggested version increment based on commit types\n- **Git Tags**: Available version tags in repository\n\n## Version Bump Logic\n- **Major**: Breaking changes detected (BREAKING CHANGE in commit)\n- **Minor**: New features detected (feat commits)\n- **Patch**: Bug fixes only (fix commits)\n\n## Git Tag Integration\n- **Tag History**: All git tags with creation dates and commit hashes\n- **Version Tracking**: Maps tags to specific commits\n- **Release Timeline**: Chronological order of releases\n\n## Use Cases\n- **Release Planning**: Determine next version number for release\n- **Version Management**: Track version history and progression\n- **Automated Versioning**: Support for automated version bumping\n- **Release Validation**: Ensure proper version increments",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-version-info": {
                    "summary": "Successful version information retrieval",
                    "value": {
                      "data": {
                        "commits": [
                          {
                            "author": "John Doe",
                            "date": "2024-01-15T10:30:00.000Z",
                            "hash": "a1b2c3d4e5f6789012345678901234567890abcd",
                            "isBreaking": false,
                            "message": "feat(auth): add OAuth2 integration",
                            "scope": "auth",
                            "shortHash": "a1b2c3d",
                            "subject": "add OAuth2 integration",
                            "type": "feat"
                          }
                        ],
                        "currentVersion": "1.2.3",
                        "recommendedBump": "minor",
                        "tags": [
                          {
                            "date": "2024-01-10T08:00:00.000Z",
                            "hash": "z9y8x7w",
                            "tag": "v1.2.3"
                          },
                          {
                            "date": "2024-01-05T14:30:00.000Z",
                            "hash": "y8x7w6v",
                            "tag": "v1.2.2"
                          }
                        ]
                      },
                      "message": "Version information retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/VersionInfoResponse"
                }
              }
            },
            "description": "Version information retrieved successfully"
          },
          "500": {
            "content": {
              "application/json": {
                "examples": {
                  "package-json-error": {
                    "summary": "Package.json read error",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "Failed to read package.json version",
                      "statusCode": 500
                    }
                  },
                  "version-error": {
                    "summary": "Version retrieval error",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "Failed to retrieve version information",
                      "statusCode": 500
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error"
          }
        },
        "summary": "Get version information and recommendations",
        "tags": [
          "Changelog"
        ]
      }
    },
    "/client-usage-tracking/daily-metrics": {
      "get": {
        "description": "Returns daily cost and usage timeseries from Langfuse observability data.\n\nWhen Langfuse is available, returns per-day totals including cost, trace count, observation count, and per-model token breakdown. When Langfuse is unavailable or disabled, returns an empty array with `source: \"local\"`.\n\n**Cache**: HTTP response cached for 15 minutes. Langfuse API results cached in-memory for 5 minutes with circuit breaker protection.\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Start date for daily metrics period",
            "example": "2026-02-01T00:00:00.000Z",
            "in": "query",
            "name": "start_date",
            "required": false,
            "schema": {
              "format": "date-time",
              "type": "string"
            }
          },
          {
            "description": "End date for daily metrics period",
            "example": "2026-03-06T23:59:59.999Z",
            "in": "query",
            "name": "end_date",
            "required": false,
            "schema": {
              "format": "date-time",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/DailyMetricsResponse"
                    },
                    "message": {
                      "example": "Daily metrics retrieved successfully",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Daily metrics retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get daily AI usage metrics from Langfuse",
        "tags": [
          "Client Usage Tracking"
        ]
      }
    },
    "/client-usage-tracking/list": {
      "get": {
        "description": "Retrieve paginated list of user's AI usage records with comprehensive filtering options.\n\n## Usage List Retrieval\nDetailed usage history with:\n- **Comprehensive Records**: Complete usage history with all operation details\n- **Advanced Filtering**: Filter by date range, operation type, model, and API key source\n- **Pagination Support**: Efficient pagination for large usage histories\n- **Detailed Metadata**: Include all request metadata and processing information\n- **Cost Tracking**: Individual cost estimates for each usage record\n\n## Filtering Options\n- **Date Range**: Filter by start and end dates for specific periods\n- **Operation Type**: Filter by specific AI operation types\n- **Model Used**: Filter by specific AI models used\n- **API Key Source**: Filter by user keys vs system keys\n- **Pagination**: Page-based navigation with configurable page size\n\n## Use Cases\n- **Usage Review**: Review detailed usage history for analysis\n- **Cost Analysis**: Analyze individual operation costs and patterns\n- **Audit Trail**: Maintain detailed audit trail of AI usage\n- **Debugging**: Investigate specific usage patterns or issues\n- **Reporting**: Generate detailed usage reports for billing or analysis\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Page number for pagination",
            "example": 1,
            "in": "query",
            "name": "page",
            "required": false,
            "schema": {
              "default": 1,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "description": "Number of records per page",
            "example": 20,
            "in": "query",
            "name": "limit",
            "required": false,
            "schema": {
              "default": 20,
              "maximum": 100,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "description": "Start date for filtering usage records",
            "example": "2024-01-01T00:00:00.000Z",
            "in": "query",
            "name": "start_date",
            "required": false,
            "schema": {
              "format": "date-time",
              "type": "string"
            }
          },
          {
            "description": "End date for filtering usage records",
            "example": "2024-01-31T23:59:59.999Z",
            "in": "query",
            "name": "end_date",
            "required": false,
            "schema": {
              "format": "date-time",
              "type": "string"
            }
          },
          {
            "description": "Filter by specific AI model",
            "example": "gpt-4o",
            "in": "query",
            "name": "model_used",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "Filter by operation type (0=TEXT_GENERATION, 1=IMAGE_ANALYSIS, etc.)",
            "example": 0,
            "in": "query",
            "name": "operation_type",
            "required": false,
            "schema": {
              "enum": [
                0,
                1,
                2,
                3,
                4,
                5,
                6
              ],
              "type": "integer"
            }
          },
          {
            "description": "Filter by API key source (0=USER_KEY, 1=SYSTEM_KEY)",
            "example": 0,
            "in": "query",
            "name": "api_key_source",
            "required": false,
            "schema": {
              "enum": [
                0,
                1
              ],
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/UsageListResponse"
                }
              }
            },
            "description": "Usage list retrieved successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Invalid date format or pagination parameters",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid query parameters"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get user usage list",
        "tags": [
          "Client Usage Tracking"
        ]
      }
    },
    "/client-usage-tracking/model-breakdown": {
      "get": {
        "description": "Returns per-model actual cost and token breakdown from Langfuse observability data.\n\nWhen Langfuse is available, returns each model's total cost, token count, request count, and P50 latency. When unavailable, returns an empty array with `source: \"local\"`.\n\n**Cache**: HTTP response cached for 15 minutes. Langfuse API results cached in-memory for 5 minutes with circuit breaker protection.\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Start date for model breakdown period",
            "example": "2026-02-01T00:00:00.000Z",
            "in": "query",
            "name": "start_date",
            "required": false,
            "schema": {
              "format": "date-time",
              "type": "string"
            }
          },
          {
            "description": "End date for model breakdown period",
            "example": "2026-03-06T23:59:59.999Z",
            "in": "query",
            "name": "end_date",
            "required": false,
            "schema": {
              "format": "date-time",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/ModelBreakdownResponse"
                    },
                    "message": {
                      "example": "Model breakdown retrieved successfully",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Model breakdown retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get per-model AI cost breakdown from Langfuse",
        "tags": [
          "Client Usage Tracking"
        ]
      }
    },
    "/client-usage-tracking/monthly/{year}/{month}": {
      "get": {
        "description": "Retrieve detailed monthly usage statistics for a specific year and month with daily breakdowns.\n\n## Monthly Usage Analysis\nComprehensive monthly reporting with:\n- **Monthly Totals**: Total tokens, requests, and costs for the entire month\n- **Daily Breakdown**: Day-by-day usage analysis throughout the month\n- **Operation Summary**: Monthly summary by operation type\n- **Trend Analysis**: Usage patterns and trends within the month\n- **Cost Tracking**: Monthly cost analysis and daily spending patterns\n\n## Daily Analytics\n- **Daily Usage**: Token consumption and request counts per day\n- **Daily Costs**: Cost breakdown by day for budget tracking\n- **Usage Patterns**: Identify peak usage days and patterns\n- **Efficiency Metrics**: Daily efficiency and performance analysis\n- **Trend Identification**: Spot usage trends and anomalies\n\n## Use Cases\n- **Monthly Reporting**: Generate monthly usage reports for billing\n- **Budget Tracking**: Monitor monthly spending against budgets\n- **Usage Planning**: Plan future usage based on historical patterns\n- **Cost Analysis**: Analyze monthly cost trends and optimization opportunities\n- **Performance Monitoring**: Track monthly performance and efficiency metrics\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Year for monthly usage statistics",
            "example": 2024,
            "in": "path",
            "name": "year",
            "required": true,
            "schema": {
              "maximum": 2100,
              "minimum": 2000,
              "type": "integer"
            }
          },
          {
            "description": "Month for usage statistics (1-12)",
            "example": 1,
            "in": "path",
            "name": "month",
            "required": true,
            "schema": {
              "maximum": 12,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MonthlyUsageResponse"
                }
              }
            },
            "description": "Monthly usage statistics retrieved successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Invalid year or month value",
                      "type": "string"
                    },
                    "fieldErrors": {
                      "additionalProperties": {
                        "items": {
                          "type": "string"
                        },
                        "type": "array"
                      },
                      "example": {
                        "month": [
                          "Month must be between 1 and 12"
                        ],
                        "year": [
                          "Year must be between 2000 and 2100"
                        ]
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid year or month parameters"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "No usage data found for the specified month",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "No usage data found for the specified month"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get monthly usage statistics",
        "tags": [
          "Client Usage Tracking"
        ]
      }
    },
    "/client-usage-tracking/record": {
      "post": {
        "description": "Record AI usage from client-side operations for tracking, analytics, and cost management.\n\n## Usage Recording (使用量記録)\nComprehensive usage tracking with:\n- **Token Consumption**: Accurate tracking of prompt and completion tokens\n- **Cost Estimation**: Real-time cost calculation based on current pricing\n- **Operation Classification**: Categorize by operation type (text, image, document, web)\n- **API Key Attribution**: Track usage by API key source (user vs system)\n- **Performance Monitoring**: Record processing times for optimization\n- **Metadata Capture**: Store additional context about operations\n\n## Operation Types Supported\n- **Text Generation (0)**: GPT-based text generation and completion\n- **Image Analysis (1)**: Vision model analysis of images and visual content\n- **PDF Analysis (2)**: Document analysis and content extraction from PDFs\n- **DOCX Analysis (3)**: Document analysis and content extraction from Word documents\n- **Embeddings (4)**: Vector embeddings generation for semantic search\n- **Web Scrape (5)**: Web content extraction and analysis\n- **Web Search (6)**: Web search operations and result analysis\n\n## API Key Source Tracking\n- **User Key (0)**: Usage from user-provided API keys\n- **System Key (1)**: Usage from system-provided API keys\n- **Billing Attribution**: Proper cost attribution for billing and budgeting\n- **Usage Limits**: Enforce usage limits based on key source\n- **Analytics Segmentation**: Separate analytics for different key sources\n\n## Cost Management\n- **Real-Time Calculation**: Immediate cost estimation based on token usage\n- **Pricing Updates**: Automatic adjustment to current AI service pricing\n- **Budget Monitoring**: Track spending against budgets and limits\n- **Cost Optimization**: Identify expensive operations for optimization\n- **Billing Integration**: Support for billing and invoicing systems\n\n## Use Cases\n- **Usage Analytics**: Track AI usage patterns and trends\n- **Cost Management**: Monitor and control AI service costs\n- **Performance Optimization**: Identify slow or expensive operations\n- **Budget Planning**: Plan AI usage budgets and limits\n- **Billing Transparency**: Provide detailed usage breakdowns for billing\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "firecrawl_scrape": {
                  "summary": "Firecrawl web scraping usage",
                  "value": {
                    "api_key_source": 1,
                    "completion_tokens": 0,
                    "cost_estimate": "0.01",
                    "model_used": "firecrawl-scrape",
                    "operation_type": 5,
                    "processing_time_ms": 3500,
                    "prompt_tokens": 1,
                    "request_id": "770e8400-e29b-41d4-a716-446655440002",
                    "request_metadata": {
                      "format": "markdown",
                      "url": "https://example.com"
                    },
                    "total_tokens": 1
                  }
                },
                "pdf_analysis": {
                  "summary": "PDF document analysis usage",
                  "value": {
                    "api_key_source": 0,
                    "completion_tokens": 800,
                    "cost_estimate": "0.0645",
                    "model_used": "gpt-4o",
                    "operation_type": 2,
                    "processing_time_ms": 5200,
                    "prompt_tokens": 3500,
                    "request_id": "660e8400-e29b-41d4-a716-446655440001",
                    "request_metadata": {
                      "document_type": "pdf",
                      "extraction_type": "full_content",
                      "file_size_mb": 4.7,
                      "page_count": 12
                    },
                    "total_tokens": 4300
                  }
                },
                "text_generation": {
                  "summary": "Text generation with idempotency key",
                  "value": {
                    "api_key_source": 0,
                    "completion_tokens": 75,
                    "cost_estimate": "0.0045",
                    "model_used": "gpt-4o",
                    "operation_type": 0,
                    "processing_time_ms": 1250,
                    "prompt_tokens": 150,
                    "request_id": "550e8400-e29b-41d4-a716-446655440000",
                    "request_metadata": {
                      "language": "japanese",
                      "operation": "document_summary"
                    },
                    "total_tokens": 225
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/RecordClientUsageRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RecordUsageResponse"
                }
              }
            },
            "description": "Usage recorded successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Token count validation failed",
                      "type": "string"
                    },
                    "fieldErrors": {
                      "additionalProperties": {
                        "items": {
                          "type": "string"
                        },
                        "type": "array"
                      },
                      "example": {
                        "cost_estimate": [
                          "Cost estimate exceeds maximum allowed per request"
                        ],
                        "total_tokens": [
                          "Total tokens must equal prompt + completion tokens"
                        ]
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid usage data or validation errors"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Too many usage records. Please slow down.",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Usage recording rate limit exceeded"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Record client-side AI usage",
        "tags": [
          "Client Usage Tracking"
        ]
      }
    },
    "/client-usage-tracking/stats": {
      "get": {
        "description": "Retrieve comprehensive usage statistics for the authenticated user.\n\nWhen `source=langfuse` is passed and Langfuse is available, returns **actual** costs, latency percentiles, and error counts from Langfuse observability. Otherwise falls back to **estimated** costs from `client_usage_tokens`.\n\nPass `group_by=feature` (or camelCase `groupBy=feature`) to include `featureBreakdown` (aggregated from local `client_usage_tokens.feature`, including when source=langfuse for headline metrics).\n\nThe response always includes a `source` field inside `data` indicating the data origin: `\"langfuse\"` or `\"local\"`.\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Start date for statistics period",
            "example": "2024-01-01T00:00:00.000Z",
            "in": "query",
            "name": "start_date",
            "required": false,
            "schema": {
              "format": "date-time",
              "type": "string"
            }
          },
          {
            "description": "End date for statistics period",
            "example": "2024-01-31T23:59:59.999Z",
            "in": "query",
            "name": "end_date",
            "required": false,
            "schema": {
              "format": "date-time",
              "type": "string"
            }
          },
          {
            "description": "Preferred data source. \"langfuse\" returns actual costs when available; \"local\" always uses client_usage_tokens.",
            "example": "langfuse",
            "in": "query",
            "name": "source",
            "required": false,
            "schema": {
              "enum": [
                "langfuse",
                "local"
              ],
              "type": "string"
            }
          },
          {
            "description": "When \"feature\", includes featureBreakdown: cost/tokens/requests keyed by UsageFeature (advisor_chat, advisor_rag_retrieval, …). Frontend may send camelCase `groupBy` (converted to `group_by`).",
            "example": "feature",
            "in": "query",
            "name": "group_by",
            "required": false,
            "schema": {
              "enum": [
                "feature"
              ],
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "langfuse_source": {
                    "summary": "Langfuse actual data",
                    "value": {
                      "data": {
                        "apiKeySourceBreakdown": {
                          "0": {
                            "cost": 5.45,
                            "requests": 12,
                            "tokens": 3750
                          }
                        },
                        "avgScore": 0.82,
                        "errorCount": 2,
                        "latencyP50Ms": 1250,
                        "latencyP95Ms": 3800,
                        "operationBreakdown": {
                          "document-analysis": {
                            "cost": 12.75,
                            "requests": 25,
                            "tokens": 8500
                          }
                        },
                        "source": "langfuse",
                        "totalCost": 23.45,
                        "totalRequests": 42,
                        "totalTokens": 15750
                      },
                      "message": "Usage statistics retrieved successfully",
                      "success": true
                    }
                  },
                  "local_fallback": {
                    "summary": "Local estimated data (Langfuse unavailable)",
                    "value": {
                      "data": {
                        "apiKeySourceBreakdown": {
                          "0": {
                            "cost": 5.45,
                            "requests": 12,
                            "tokens": 3750
                          }
                        },
                        "operationBreakdown": {
                          "0": {
                            "cost": 12.75,
                            "requests": 25,
                            "tokens": 8500
                          }
                        },
                        "source": "local",
                        "totalCost": 23.45,
                        "totalRequests": 42,
                        "totalTokens": 15750
                      },
                      "message": "Usage statistics retrieved successfully",
                      "success": true
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/EnhancedUsageStats"
                }
              }
            },
            "description": "Usage statistics retrieved successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Invalid date format or date range",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid date parameters"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get user usage statistics (enhanced with Langfuse)",
        "tags": [
          "Client Usage Tracking"
        ]
      }
    },
    "/client-usage-tracking/system-stats": {
      "get": {
        "description": "Retrieve system-wide usage statistics across all users for administrative monitoring and capacity planning.\n\n## System-Wide Analytics\nComprehensive system analytics including:\n- **Global Usage Metrics**: Total system usage across all users and operations\n- **User Distribution**: Usage distribution across different users\n- **Operation Analysis**: System-wide operation type analysis and trends\n- **Capacity Planning**: Data for system capacity planning and scaling\n- **Performance Monitoring**: System-wide performance metrics and optimization insights\n\n## Administrative Insights\n- **System Load**: Overall system usage and load patterns\n- **Resource Utilization**: AI service resource utilization across the system\n- **Cost Analysis**: System-wide cost analysis and budget planning\n- **User Patterns**: Aggregate user usage patterns and trends\n- **Optimization Opportunities**: System-wide optimization opportunities\n\n## Use Cases\n- **System Monitoring**: Monitor overall system usage and performance\n- **Capacity Planning**: Plan system capacity and scaling requirements\n- **Cost Management**: System-wide cost analysis and budget planning\n- **Performance Optimization**: Identify system-wide optimization opportunities\n- **Administrative Reporting**: Generate administrative reports and analytics\n\n## Authentication\nRequires valid Bearer token in Authorization header with administrative privileges.",
        "parameters": [
          {
            "description": "Start date for system statistics period",
            "example": "2024-01-01T00:00:00.000Z",
            "in": "query",
            "name": "start_date",
            "required": false,
            "schema": {
              "format": "date-time",
              "type": "string"
            }
          },
          {
            "description": "End date for system statistics period",
            "example": "2024-01-31T23:59:59.999Z",
            "in": "query",
            "name": "end_date",
            "required": false,
            "schema": {
              "format": "date-time",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/UsageStatsResponse"
                }
              }
            },
            "description": "System usage statistics retrieved successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Invalid date format or date range",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid date parameters"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Administrative privileges required for system statistics",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Insufficient privileges for system statistics"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get system-wide usage statistics",
        "tags": [
          "Client Usage Tracking"
        ]
      }
    },
    "/clients": {
      "get": {
        "description": "Retrieves a paginated list of clients with comprehensive search and sorting capabilities.\n      \n## Pagination Features\n- **Page-based pagination**: Navigate through results using page numbers\n- **Configurable page size**: Control number of items per page (1-100)\n- **Total count**: Get total number of items and pages\n- **Navigation flags**: Know if next/previous pages are available\n\n## Search Functionality\n- **Multi-field search**: Search across name, furigana, corporate number, contact person, and email\n- **Case-insensitive**: Search works regardless of case\n- **Partial matching**: Find clients with partial text matches\n- **Japanese text support**: Full support for Japanese characters and furigana\n\n## Sorting Options\n- **Multiple sort fields**: Sort by name, furigana, corporate number, contact person, or timestamps\n- **Sort direction**: Ascending or descending order\n- **Default sorting**: By creation date (newest first)\n\n## User Scoping\n- **User-specific results**: Only returns clients created by the authenticated user\n- **Soft delete filtering**: Excludes deleted clients from results\n- **Secure access**: Requires authentication for all operations",
        "parameters": [
          {
            "description": "Page number for pagination (starts from 1)",
            "in": "query",
            "name": "page_number",
            "required": true,
            "schema": {
              "example": 1,
              "minimum": 1,
              "type": "number"
            }
          },
          {
            "description": "Number of items per page (maximum 100)",
            "in": "query",
            "name": "page_size",
            "required": true,
            "schema": {
              "example": 10,
              "maximum": 100,
              "minimum": 1,
              "type": "number"
            }
          },
          {
            "description": "Search term to filter clients by name, furigana, corporate number, contact person, or email",
            "in": "query",
            "name": "search",
            "required": false,
            "schema": {
              "example": "サンプル",
              "type": "string"
            }
          },
          {
            "description": "Field to sort by",
            "in": "query",
            "name": "sort_by",
            "required": false,
            "schema": {
              "enum": [
                "name",
                "furigana",
                "corporate_number",
                "contact_person",
                "created_at",
                "updated_at"
              ],
              "example": "created_at",
              "type": "string"
            }
          },
          {
            "description": "Sort order (ascending or descending)",
            "in": "query",
            "name": "sort_order",
            "required": false,
            "schema": {
              "enum": [
                "asc",
                "desc"
              ],
              "example": "desc",
              "type": "string"
            }
          },
          {
            "description": "Filter by client type (0=Customer/得意先, 1=Supplier/仕入先, 2=Both/両方)",
            "in": "query",
            "name": "client_type",
            "required": false,
            "schema": {
              "enum": [
                0,
                1,
                2
              ],
              "type": "number"
            }
          },
          {
            "description": "Filter to only qualified invoice issuers (適格請求書発行事業者)",
            "in": "query",
            "name": "is_qualified",
            "required": false,
            "schema": {
              "type": "boolean"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "empty-list": {
                    "summary": "Empty client list",
                    "value": {
                      "data": {
                        "items": [],
                        "pagination": {
                          "currentPage": 1,
                          "hasNext": false,
                          "hasPrevious": false,
                          "pageSize": 10,
                          "totalItems": 0,
                          "totalPages": 1
                        }
                      },
                      "message": "Clients retrieved successfully",
                      "statusCode": 200
                    }
                  },
                  "search-results": {
                    "summary": "Search results for \"サンプル\"",
                    "value": {
                      "data": {
                        "items": [
                          {
                            "address": "東京都渋谷区サンプル１丁目２番３号",
                            "client_type": 0,
                            "contact_person": "山田太郎",
                            "corporate_number": "1234567890123",
                            "created_at": "2024-01-15T10:30:00.000Z",
                            "created_by": "123e4567-e89b-12d3-a456-426614174000",
                            "deleted_at": null,
                            "deleted_by": null,
                            "email": "contact@example.co.jp",
                            "furigana": "サンプルカブシキガイシャ",
                            "id": "550e8400-e29b-41d4-a716-446655440000",
                            "is_deleted": false,
                            "name": "サンプル株式会社",
                            "phone": "03-0000-0000",
                            "registration_number": "T1234567890123",
                            "updated_at": "2024-01-15T10:30:00.000Z",
                            "updated_by": null
                          }
                        ],
                        "pagination": {
                          "currentPage": 1,
                          "hasNext": false,
                          "hasPrevious": false,
                          "pageSize": 10,
                          "totalItems": 1,
                          "totalPages": 1
                        }
                      },
                      "message": "Clients retrieved successfully",
                      "statusCode": 200
                    }
                  },
                  "successful-list": {
                    "summary": "Successful client list retrieval",
                    "value": {
                      "data": {
                        "items": [
                          {
                            "address": "東京都渋谷区サンプル１丁目２番３号",
                            "client_type": 0,
                            "contact_person": "山田太郎",
                            "corporate_number": "1234567890123",
                            "created_at": "2024-01-15T10:30:00.000Z",
                            "created_by": "123e4567-e89b-12d3-a456-426614174000",
                            "deleted_at": null,
                            "deleted_by": null,
                            "email": "contact@example.co.jp",
                            "furigana": "サンプルカブシキガイシャ",
                            "id": "550e8400-e29b-41d4-a716-446655440000",
                            "is_deleted": false,
                            "name": "サンプル株式会社",
                            "phone": "03-0000-0000",
                            "registration_number": "T1234567890123",
                            "updated_at": "2024-01-15T10:30:00.000Z",
                            "updated_by": null
                          },
                          {
                            "address": "東京都新宿区テスト２丁目３番４号",
                            "client_type": 0,
                            "contact_person": "佐藤花子",
                            "corporate_number": "9876543210987",
                            "created_at": "2024-01-14T15:45:00.000Z",
                            "created_by": "123e4567-e89b-12d3-a456-426614174000",
                            "deleted_at": null,
                            "deleted_by": null,
                            "email": "info@test-company.co.jp",
                            "furigana": "テストカブシキガイシャ",
                            "id": "660f9511-f40c-52e5-b827-557766551111",
                            "is_deleted": false,
                            "name": "テスト株式会社",
                            "phone": "03-1111-1111",
                            "registration_number": "T9876543210987",
                            "updated_at": "2024-01-14T15:45:00.000Z",
                            "updated_by": null
                          }
                        ],
                        "pagination": {
                          "currentPage": 1,
                          "hasNext": true,
                          "hasPrevious": false,
                          "pageSize": 10,
                          "totalItems": 25,
                          "totalPages": 3
                        }
                      },
                      "message": "Clients retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ClientListResponse"
                }
              }
            },
            "description": "Clients retrieved successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "examples": {
                  "invalid-pagination": {
                    "summary": "Invalid pagination parameters",
                    "value": {
                      "error": "Validation Error",
                      "message": "page_number must be a positive number, page_size must be between 1 and 100",
                      "statusCode": 400
                    }
                  },
                  "invalid-sort-field": {
                    "summary": "Invalid sort field",
                    "value": {
                      "error": "Validation Error",
                      "message": "sort_by must be one of: name, furigana, corporate_number, contact_person, created_at, updated_at",
                      "statusCode": 400
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Invalid pagination parameters or query format"
          },
          "401": {
            "content": {
              "application/json": {
                "examples": {
                  "not-authenticated": {
                    "summary": "Authentication required",
                    "value": {
                      "error": "Unauthorized",
                      "message": "User not authenticated",
                      "statusCode": 401
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "User not authenticated"
          },
          "500": {
            "content": {
              "application/json": {
                "examples": {
                  "server-error": {
                    "summary": "Database or server error",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "An unexpected error occurred while retrieving clients",
                      "statusCode": 500
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get paginated list of clients",
        "tags": [
          "Client"
        ]
      },
      "post": {
        "description": "Creates a new client record in the system with comprehensive company information.\n      \n## Client Creation Process\n- Validates all required fields (name, corporate_number, contact_person)\n- Stores client information with audit trail (created_by, timestamps)\n- Supports soft delete functionality for data integrity\n- Automatically generates UUID for unique identification\n\n## Required Information\n- **Company Name**: Official registered company name\n- **Corporate Number**: Japanese corporate number (13 digits)\n- **Contact Person**: Primary contact person name\n\n## Optional Information\n- **Furigana**: Company name in katakana for pronunciation\n- **Email**: Primary contact email address\n- **Phone**: Contact phone number\n- **Address**: Registered business address\n- **Registration Number**: Invoice registration number with T prefix\n\n## Data Validation\n- Email format validation when provided\n- Corporate number format validation\n- Maximum length constraints for all text fields\n- Required field validation with detailed error messages",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "complete-client": {
                  "summary": "Complete client information",
                  "value": {
                    "address": "東京都渋谷区サンプル１丁目２番３号",
                    "client_type": 0,
                    "contact_person": "山田太郎",
                    "corporate_number": "1234567890123",
                    "email": "contact@example.co.jp",
                    "furigana": "サンプルカブシキガイシャ",
                    "name": "サンプル株式会社",
                    "phone": "03-0000-0000",
                    "registration_number": "T1234567890123"
                  }
                },
                "minimal-client": {
                  "summary": "Minimal required information",
                  "value": {
                    "contact_person": "佐藤花子",
                    "corporate_number": "9876543210987",
                    "name": "テスト株式会社"
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/CreateClientRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-creation": {
                    "summary": "Successful client creation",
                    "value": {
                      "data": {
                        "address": "東京都渋谷区サンプル１丁目２番３号",
                        "client_type": 0,
                        "contact_person": "山田太郎",
                        "corporate_number": "1234567890123",
                        "created_at": "2024-01-15T10:30:00.000Z",
                        "created_by": "123e4567-e89b-12d3-a456-426614174000",
                        "deleted_at": null,
                        "deleted_by": null,
                        "email": "contact@example.co.jp",
                        "furigana": "サンプルカブシキガイシャ",
                        "id": "550e8400-e29b-41d4-a716-446655440000",
                        "is_deleted": false,
                        "name": "サンプル株式会社",
                        "phone": "03-0000-0000",
                        "registration_number": "T1234567890123",
                        "updated_at": "2024-01-15T10:30:00.000Z",
                        "updated_by": null
                      },
                      "message": "Client created successfully",
                      "statusCode": 201
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/CreateClientSuccessResponse"
                }
              }
            },
            "description": "Client created successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "examples": {
                  "invalid-email": {
                    "summary": "Invalid email format",
                    "value": {
                      "error": "Validation Error",
                      "message": "email must be an email",
                      "statusCode": 400
                    }
                  },
                  "validation-error": {
                    "summary": "Validation error for required fields",
                    "value": {
                      "error": "Validation Error",
                      "message": "name should not be empty, corporate_number should not be empty, contact_person should not be empty",
                      "statusCode": 400
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Invalid request data or validation errors"
          },
          "401": {
            "content": {
              "application/json": {
                "examples": {
                  "not-authenticated": {
                    "summary": "Authentication required",
                    "value": {
                      "error": "Unauthorized",
                      "message": "User not authenticated",
                      "statusCode": 401
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "User not authenticated"
          },
          "409": {
            "content": {
              "application/json": {
                "examples": {
                  "duplicate-client": {
                    "summary": "Duplicate corporate number",
                    "value": {
                      "error": "Conflict",
                      "message": "Client with this corporate number already exists",
                      "statusCode": 409
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Client already exists with same corporate number"
          },
          "500": {
            "content": {
              "application/json": {
                "examples": {
                  "server-error": {
                    "summary": "Database or server error",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "An unexpected error occurred while creating the client",
                      "statusCode": 500
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create a new client",
        "tags": [
          "Client"
        ]
      }
    },
    "/clients/ai-creation": {
      "post": {
        "description": "Sends the text to the user's configured AI provider with an extraction prompt asking for companyName, companyNameFurigana, corporateNumber, contactPerson, email, phone, address and invoiceRegistrationNumber (null when absent).\n\n`data` is the provider's generateText result as returned: the parsed JSON object when the provider parsed the model's reply (Claude, Gemini), otherwise `{ content: <raw model text> }` (OpenAI always). Nothing is saved.",
        "operationId": "clientAiCreation",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ClientAICreationRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "additionalProperties": true,
                      "description": "The extracted fields when the provider parsed the reply, else { content: <raw model text> }",
                      "type": "object"
                    },
                    "message": {
                      "example": "Client data extracted successfully",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Extraction completed"
          },
          "400": {
            "description": "text missing, empty or over 10000 characters"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          },
          "503": {
            "description": "The AI provider call failed (stable AI error code in the problem details)"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Extract client details from free text with AI",
        "tags": [
          "Client"
        ]
      }
    },
    "/clients/backfill-document-links": {
      "post": {
        "description": "Migrate existing documents to use direct client_id FK by matching JSONB content.\n\n## Purpose\nOne-time utility to update existing documents that have `clientInfo.companyName`, \n`buyerInfo.companyName`, or `supplierInfo.companyName` in their JSONB content \nto also have a direct `client_id` foreign key link.\n\n## Matching Logic\nFor each document without `client_id`:\n1. Extract company names from JSONB content fields\n2. Match against user's clients (case-insensitive)\n3. Set `client_id` if match found (single match per document)\n\n## Dry Run Mode (Default)\nBy default, this endpoint runs in **dry run mode**:\n- Returns what WOULD be updated\n- Does NOT modify any data\n- Use `?dryRun=false` to actually apply changes\n\n## Authentication\nRequires valid Bearer token. Only processes documents owned by the authenticated user.\n\n## Use Cases\n- Initial migration after adding `client_id` FK\n- Re-run after adding new clients to catch previously unmatched documents\n- Preview matching before committing changes",
        "parameters": [
          {
            "description": "If true (default), preview matches without updating. Set to false to apply changes.",
            "in": "query",
            "name": "dryRun",
            "schema": {
              "default": true,
              "type": "boolean"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "actual-run": {
                    "summary": "Actual backfill result",
                    "value": {
                      "data": {
                        "matchedDocuments": 45,
                        "matches": [],
                        "totalDocuments": 150,
                        "updatedDocuments": 45
                      },
                      "message": "Backfill complete. Updated 45 documents with client links.",
                      "statusCode": 200
                    }
                  },
                  "dry-run": {
                    "summary": "Dry run result",
                    "value": {
                      "data": {
                        "matchedDocuments": 45,
                        "matches": [
                          {
                            "clientId": "550e8400-e29b-41d4-a716-446655440000",
                            "clientName": "ABC株式会社",
                            "documentId": "660f9511-f40c-52e5-b827-557766551111",
                            "documentName": "見積書_ABC株式会社",
                            "documentType": "sales_quotation",
                            "matchField": "clientInfo"
                          }
                        ],
                        "totalDocuments": 150,
                        "updatedDocuments": 0
                      },
                      "message": "Dry run complete. Found 45 documents that can be linked to clients.",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/BackfillDocumentLinksResponse"
                }
              }
            },
            "description": "Backfill operation completed"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Backfill document-client links (migration utility)",
        "tags": [
          "Client"
        ]
      }
    },
    "/clients/export": {
      "get": {
        "description": "Export trading partners list to CSV or JSON file format with proper Content-Disposition headers for browser download.\n\n## Export Formats\n\n### CSV Format (Japanese Accounting Standard)\nHeaders:\n```\n取引先名,ふりがな,法人番号,適格請求書登録番号,取引先種別,担当者,メールアドレス,電話番号,住所,書類数,取引金額,登録日\n```\n\nExample row:\n```\nサンプル商事株式会社,サンプルシヨウジ,0000000000000,T0000000000000,得意先,担当者未定,,,東京都〇〇区...,7,0,2025/12/26\n```\n\n### JSON Format\nArray of client objects with all fields in snake_case.\n\n## Response Headers\n- **Content-Type**: `text/csv; charset=utf-8` or `application/json; charset=utf-8`\n- **Content-Disposition**: `attachment; filename=\"取引先一覧-2026-01-12.csv\"`\n\n## Features\n- **BOM Prefix**: CSV includes UTF-8 BOM for Excel compatibility\n- **Proper Escaping**: CSV fields with commas/quotes are properly escaped\n- **Japanese Dates**: Date format YYYY/MM/DD\n- **Statistics Included**: Each row includes document count and total transaction amount\n\n## Frontend Integration\n```javascript\n// Direct browser navigation triggers download\nwindow.location.href = '/api/clients/export?format=csv&client_type=1&is_qualified=true'\n```",
        "parameters": [
          {
            "description": "Export format (csv or json)",
            "in": "query",
            "name": "format",
            "required": false,
            "schema": {
              "default": "csv",
              "enum": [
                "csv",
                "json"
              ],
              "type": "string"
            }
          },
          {
            "description": "Filter by client type (0=Customer/得意先, 1=Supplier/仕入先, 2=Both/両方). Omit for all.",
            "in": "query",
            "name": "client_type",
            "required": false,
            "schema": {
              "enum": [
                0,
                1,
                2
              ],
              "type": "number"
            }
          },
          {
            "description": "Filter to only qualified invoice issuers (適格請求書発行事業者)",
            "in": "query",
            "name": "is_qualified",
            "required": false,
            "schema": {
              "type": "boolean"
            }
          },
          {
            "description": "Search filter for name, furigana, corporate number, contact, email",
            "in": "query",
            "name": "search",
            "required": false,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "items": {
                    "properties": {
                      "address": {
                        "example": "東京都渋谷区...",
                        "type": "string"
                      },
                      "client_type": {
                        "example": 0,
                        "type": "number"
                      },
                      "client_type_label": {
                        "example": "得意先",
                        "type": "string"
                      },
                      "contact_person": {
                        "example": "山田太郎",
                        "type": "string"
                      },
                      "corporate_number": {
                        "example": "1234567890123",
                        "type": "string"
                      },
                      "created_at": {
                        "format": "date-time",
                        "type": "string"
                      },
                      "document_count": {
                        "example": 5,
                        "type": "number"
                      },
                      "email": {
                        "example": "contact@example.co.jp",
                        "type": "string"
                      },
                      "furigana": {
                        "example": "サンプルカブシキガイシャ",
                        "type": "string"
                      },
                      "id": {
                        "format": "uuid",
                        "type": "string"
                      },
                      "name": {
                        "example": "サンプル株式会社",
                        "type": "string"
                      },
                      "phone": {
                        "example": "03-0000-0000",
                        "type": "string"
                      },
                      "registration_number": {
                        "example": "T1234567890123",
                        "type": "string"
                      },
                      "total_amount": {
                        "example": 150000,
                        "type": "number"
                      }
                    },
                    "type": "object"
                  },
                  "type": "array"
                }
              },
              "text/csv": {
                "example": "取引先名,ふりがな,法人番号,適格請求書登録番号,取引先種別,担当者,メールアドレス,電話番号,住所,書類数,取引金額,登録日\r\nサンプル株式会社,サンプルカブシキガイシャ,1234567890123,T1234567890123,得意先,山田太郎,contact@example.co.jp,03-0000-0000,東京都渋谷区...,5,150000,2026/01/10",
                "schema": {
                  "format": "binary",
                  "type": "string"
                }
              }
            },
            "description": "File download with Content-Disposition header",
            "headers": {
              "Content-Disposition": {
                "description": "Attachment filename",
                "schema": {
                  "example": "attachment; filename=\"取引先一覧-2026-01-12.csv\"",
                  "type": "string"
                }
              }
            }
          },
          "401": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "User not authenticated"
          },
          "500": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Export clients to CSV or JSON (取引先エクスポート)",
        "tags": [
          "Client"
        ]
      }
    },
    "/clients/scrape-company-data": {
      "get": {
        "description": "Extracts comprehensive company information from Japanese government databases using corporate number.\n      \n## Data Sources\n- **Primary**: Invoice registration site (invoice-kohyo.nta.go.jp) - More structured data\n- **Fallback**: Corporate number site (houjin-bangou.nta.go.jp) - Basic company information\n\n## Supported Formats\n- Corporate numbers with or without 'T' prefix\n- 13-digit format (automatically padded if shorter)\n- Both individual and corporate entities\n\n## Extracted Information\n- Official company name (Japanese)\n- Company name furigana (katakana reading)\n- Registered business address\n- Corporate number (normalized)\n- Last update date from government records\n- Invoice registration details (when available)\n\n## Error Handling\n- Invalid corporate numbers return 404\n- Website structure changes handled gracefully\n- Multi-site fallback ensures maximum success rate",
        "parameters": [
          {
            "description": "Japanese corporate number (13 digits, with or without T prefix)",
            "in": "query",
            "name": "corporate_number",
            "required": true,
            "schema": {
              "example": "1234567890123",
              "pattern": "^T?\\d{13}$",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-scrape": {
                    "summary": "Successful company data extraction",
                    "value": {
                      "data": {
                        "address": "東京都渋谷区サンプル１丁目２番３号",
                        "companyName": "サンプル株式会社",
                        "companyNameFurigana": "サンプルカブシキガイシャ",
                        "corporateNumber": "1234567890123",
                        "lastUpdated": "令和6年1月31日",
                        "registrationDate": "令和5年10月1日",
                        "registrationNumber": "T1234567890123"
                      },
                      "message": "Company data scraped successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/CompanyDataSuccessResponse"
                }
              }
            },
            "description": "Company data scraped successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "examples": {
                  "invalid-format": {
                    "summary": "Invalid corporate number format",
                    "value": {
                      "error": "Validation Error",
                      "message": "Corporate number must be 13 digits with optional T prefix",
                      "statusCode": 400
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Invalid corporate number format"
          },
          "401": {
            "content": {
              "application/json": {
                "examples": {
                  "not-authenticated": {
                    "summary": "Authentication required",
                    "value": {
                      "error": "Unauthorized",
                      "message": "User not authenticated",
                      "statusCode": 401
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "User not authenticated"
          },
          "404": {
            "content": {
              "application/json": {
                "examples": {
                  "company-not-found": {
                    "summary": "Company not found in government databases",
                    "value": {
                      "error": "Not Found",
                      "message": "Company information not found. The corporate number may be invalid or the website structure may have changed.",
                      "statusCode": 404
                    }
                  },
                  "scraping-failed": {
                    "summary": "Failed to scrape from both government websites",
                    "value": {
                      "error": "Scraping Error",
                      "message": "Failed to scrape company data from both government websites. Corporate number: 1234567890123",
                      "statusCode": 404
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Company not found or invalid corporate number"
          },
          "429": {
            "content": {
              "application/json": {
                "examples": {
                  "rate-limited": {
                    "summary": "Too many requests",
                    "value": {
                      "error": "Rate Limit Exceeded",
                      "message": "Too many scraping requests. Please try again later.",
                      "statusCode": 429
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Rate limit exceeded"
          },
          "500": {
            "content": {
              "application/json": {
                "examples": {
                  "server-error": {
                    "summary": "Internal server error",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "An unexpected error occurred while processing the request",
                      "statusCode": 500
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Scrape company data from Japanese government websites",
        "tags": [
          "Client"
        ]
      }
    },
    "/clients/with-stats": {
      "get": {
        "description": "Retrieves a paginated list of trading partners with embedded statistics for dashboard optimization.\n\n## Trading Partner Types (取引先タイプ)\n- **0 - Customer (顧客)**: They buy from us\n- **1 - Supplier (仕入先)**: We buy from them  \n- **2 - Both (両方)**: Bidirectional trading relationship\n\n## Embedded Statistics\nEach client includes:\n- **invoiceCount**: Number of invoices linked to this client\n- **quotationCount**: Number of quotations linked to this client\n- **documentCount**: Total number of ALL documents (all types) linked to this client\n- **totalAmount**: Sum of invoice + quotation amounts\n- **lastActivityDate**: Most recent document activity\n\n## v4.28 Optimization\n**Performance improved from N+1 to 3 queries:**\n- Before: 1 query for clients + N queries for stats (one per client)\n- After: 1 query for clients + 1 aggregation for documents + 1 aggregation for invoices\n\nFor 50 clients, this reduces queries from 51 to 3 (~95% reduction).\n\n## Query Parameters\nUse `include_stats=true` to enable inline statistics (enabled by default for this endpoint).",
        "parameters": [
          {
            "description": "Page number (starts from 1)",
            "in": "query",
            "name": "page_number",
            "required": false,
            "schema": {
              "default": 1,
              "minimum": 1,
              "type": "number"
            }
          },
          {
            "description": "Items per page",
            "in": "query",
            "name": "page_size",
            "required": false,
            "schema": {
              "default": 20,
              "maximum": 100,
              "minimum": 1,
              "type": "number"
            }
          },
          {
            "description": "Filter by client type (0=Customer, 1=Supplier, 2=Both)",
            "in": "query",
            "name": "client_type",
            "required": false,
            "schema": {
              "enum": [
                0,
                1,
                2
              ],
              "type": "number"
            }
          },
          {
            "description": "Search term for name, furigana, corporate number",
            "in": "query",
            "name": "search",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "Include inline statistics with each client (v4.28+). Enabled by default for this endpoint.",
            "in": "query",
            "name": "include_stats",
            "required": false,
            "schema": {
              "default": true,
              "type": "boolean"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "with-stats": {
                    "summary": "Clients with inline statistics (v4.28+)",
                    "value": {
                      "data": {
                        "items": [
                          {
                            "client_type": 0,
                            "corporate_number": "1234567890123",
                            "furigana": "サンプルカブシキガイシャ",
                            "id": "550e8400-e29b-41d4-a716-446655440000",
                            "name": "サンプル株式会社",
                            "registration_number": "T1234567890123",
                            "stats": {
                              "documentCount": 33,
                              "invoiceCount": 15,
                              "lastActivityDate": "2026-01-10T10:30:00.000Z",
                              "quotationCount": 8,
                              "totalAmount": 3500000
                            }
                          }
                        ],
                        "pagination": {
                          "currentPage": 1,
                          "hasNext": true,
                          "hasPrevious": false,
                          "pageSize": 20,
                          "totalItems": 25,
                          "totalPages": 2
                        }
                      },
                      "message": "Clients with stats retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ClientsWithStatsResponse"
                }
              }
            },
            "description": "Clients with stats retrieved successfully"
          },
          "401": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "User not authenticated"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get clients with statistics (取引先一覧 + 統計) - Optimized v4.28",
        "tags": [
          "Client"
        ]
      }
    },
    "/clients/{client_id}": {
      "delete": {
        "description": "Performs a soft delete on a client record, marking it as deleted while preserving data integrity.\n      \n## Soft Delete Process\n- **Data Preservation**: Client data is not physically removed from the database\n- **Audit Trail**: Maintains complete audit trail with deletion timestamp and user\n- **Referential Integrity**: Preserves relationships with other entities (expenses, documents)\n- **Recovery Capability**: Deleted clients can potentially be restored if needed\n\n## Security Features\n- **User Scoping**: Users can only delete clients they created\n- **Authentication Required**: Bearer token authentication mandatory\n- **Authorization Check**: Verifies user ownership before deletion\n- **Validation**: Ensures client exists and is not already deleted\n\n## Business Impact\n- **Data Safety**: Prevents accidental data loss through soft delete mechanism\n- **Compliance**: Maintains data for audit and compliance requirements\n- **Relationships**: Associated data (expenses, documents) remains intact\n- **Reporting**: Historical data remains available for reporting purposes",
        "parameters": [
          {
            "description": "Unique identifier of the client to delete",
            "in": "path",
            "name": "client_id",
            "required": true,
            "schema": {
              "example": "550e8400-e29b-41d4-a716-446655440000",
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-deletion": {
                    "summary": "Successful client deletion",
                    "value": {
                      "message": "Client deleted successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/DeleteClientSuccessResponse"
                }
              }
            },
            "description": "Client deleted successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "examples": {
                  "invalid-uuid": {
                    "summary": "Invalid UUID format",
                    "value": {
                      "error": "Validation Error",
                      "message": "client_id must be a valid UUID",
                      "statusCode": 400
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Invalid client ID format"
          },
          "401": {
            "content": {
              "application/json": {
                "examples": {
                  "not-authenticated": {
                    "summary": "Authentication required",
                    "value": {
                      "error": "Unauthorized",
                      "message": "User not authenticated",
                      "statusCode": 401
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "User not authenticated"
          },
          "403": {
            "content": {
              "application/json": {
                "examples": {
                  "not-authorized": {
                    "summary": "User does not own this client",
                    "value": {
                      "error": "Forbidden",
                      "message": "You are not authorized to delete this client",
                      "statusCode": 403
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "User not authorized to delete this client"
          },
          "404": {
            "content": {
              "application/json": {
                "examples": {
                  "already-deleted": {
                    "summary": "Client already deleted",
                    "value": {
                      "error": "Not Found",
                      "message": "Client has already been deleted",
                      "statusCode": 404
                    }
                  },
                  "client-not-found": {
                    "summary": "Client does not exist",
                    "value": {
                      "error": "Not Found",
                      "message": "Client not found",
                      "statusCode": 404
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Client not found or already deleted"
          },
          "500": {
            "content": {
              "application/json": {
                "examples": {
                  "server-error": {
                    "summary": "Database or server error",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "An unexpected error occurred while deleting the client",
                      "statusCode": 500
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Delete a client (soft delete)",
        "tags": [
          "Client"
        ]
      },
      "get": {
        "description": "Retrieves detailed information for a specific client by their unique identifier.\n      \n## Client Retrieval Process\n- **User Scoping**: Only returns clients created by the authenticated user\n- **Soft Delete Filtering**: Excludes deleted clients from results\n- **Detailed Information**: Returns complete client record with all fields\n- **Security**: Requires authentication and user ownership validation\n\n## Retrieved Information\n- **Basic Details**: Company name, furigana, corporate number\n- **Contact Information**: Contact person, email, phone number\n- **Business Details**: Address, registration number, client type\n- **Audit Trail**: Creation and update timestamps, user tracking\n- **Status Information**: Deletion status and related metadata\n\n## Use Cases\n- **Client Profile Display**: Show complete client information in UI\n- **Data Verification**: Validate client details before operations\n- **Relationship Management**: Access client data for business operations\n- **Audit Requirements**: Review client information for compliance",
        "parameters": [
          {
            "description": "Unique identifier of the client to retrieve",
            "in": "path",
            "name": "client_id",
            "required": true,
            "schema": {
              "example": "550e8400-e29b-41d4-a716-446655440000",
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-retrieval": {
                    "summary": "Successful client retrieval",
                    "value": {
                      "data": {
                        "address": "東京都渋谷区サンプル１丁目２番３号",
                        "client_type": 0,
                        "contact_person": "山田太郎",
                        "corporate_number": "1234567890123",
                        "created_at": "2024-01-15T10:30:00.000Z",
                        "created_by": "123e4567-e89b-12d3-a456-426614174000",
                        "deleted_at": null,
                        "deleted_by": null,
                        "email": "contact@example.co.jp",
                        "furigana": "サンプルカブシキガイシャ",
                        "id": "550e8400-e29b-41d4-a716-446655440000",
                        "is_deleted": false,
                        "name": "サンプル株式会社",
                        "phone": "03-0000-0000",
                        "registration_number": "T1234567890123",
                        "updated_at": "2024-01-15T10:30:00.000Z",
                        "updated_by": null
                      },
                      "message": "Client retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/ClientResponse"
                    },
                    "message": {
                      "example": "Client retrieved successfully",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "required": [
                    "statusCode",
                    "message",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Client retrieved successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "examples": {
                  "invalid-uuid": {
                    "summary": "Invalid UUID format",
                    "value": {
                      "error": "Validation Error",
                      "message": "client_id must be a valid UUID",
                      "statusCode": 400
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Invalid client ID format"
          },
          "401": {
            "content": {
              "application/json": {
                "examples": {
                  "not-authenticated": {
                    "summary": "Authentication required",
                    "value": {
                      "error": "Unauthorized",
                      "message": "User not authenticated",
                      "statusCode": 401
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "User not authenticated"
          },
          "403": {
            "content": {
              "application/json": {
                "examples": {
                  "not-authorized": {
                    "summary": "User does not own this client",
                    "value": {
                      "error": "Forbidden",
                      "message": "You are not authorized to access this client",
                      "statusCode": 403
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "User not authorized to access this client"
          },
          "404": {
            "content": {
              "application/json": {
                "examples": {
                  "client-deleted": {
                    "summary": "Client has been deleted",
                    "value": {
                      "error": "Not Found",
                      "message": "Client has been deleted",
                      "statusCode": 404
                    }
                  },
                  "client-not-found": {
                    "summary": "Client does not exist",
                    "value": {
                      "error": "Not Found",
                      "message": "Client not found",
                      "statusCode": 404
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Client not found or deleted"
          },
          "500": {
            "content": {
              "application/json": {
                "examples": {
                  "server-error": {
                    "summary": "Database or server error",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "An unexpected error occurred while retrieving the client",
                      "statusCode": 500
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get client by ID",
        "tags": [
          "Client"
        ]
      },
      "put": {
        "description": "Updates an existing client record with partial data. Only include fields that need to be changed.\n      \n## Partial Updates\n- Send only the fields you want to update\n- Fields not included in the request remain unchanged\n- Null values can be used to clear optional fields\n\n## Validation\n- **Duplicate Check**: Corporate number and name must be unique per user\n- **Format Validation**: Corporate number must be 13 digits, email must be valid format\n- **Field Constraints**: All text fields have maximum length limits\n\n## Authorization\n- Only the user who created the client can update it\n- Requires valid Bearer token authentication\n\n## Audit Trail\n- Updates the `updated_at` timestamp automatically\n- Original `created_by` and `created_at` are preserved",
        "parameters": [
          {
            "description": "Unique identifier of the client to update",
            "in": "path",
            "name": "client_id",
            "required": true,
            "schema": {
              "example": "550e8400-e29b-41d4-a716-446655440000",
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "update-address": {
                  "summary": "Update company address",
                  "value": {
                    "address": "東京都新宿区新住所１丁目２番３号"
                  }
                },
                "update-all": {
                  "summary": "Update multiple fields",
                  "value": {
                    "address": "東京都渋谷区新住所１丁目２番３号",
                    "contact_person": "山田太郎",
                    "email": "new-contact@example.co.jp",
                    "furigana": "シンサンプルカブシキガイシャ",
                    "name": "新サンプル株式会社"
                  }
                },
                "update-contact": {
                  "summary": "Update contact information",
                  "value": {
                    "contact_person": "鈴木花子",
                    "email": "suzuki@example.co.jp",
                    "phone": "03-1234-5678"
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/UpdateClientRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-update": {
                    "summary": "Successful client update",
                    "value": {
                      "data": {
                        "address": "東京都渋谷区新住所１丁目２番３号",
                        "client_type": 0,
                        "contact_person": "山田太郎",
                        "corporate_number": "1234567890123",
                        "created_at": "2024-01-15T10:30:00.000Z",
                        "email": "new-contact@example.co.jp",
                        "furigana": "シンサンプルカブシキガイシャ",
                        "id": "550e8400-e29b-41d4-a716-446655440000",
                        "name": "新サンプル株式会社",
                        "phone": "03-0000-0000",
                        "registration_number": "T1234567890123",
                        "updated_at": "2024-01-20T14:00:00.000Z"
                      },
                      "message": "Client updated successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/UpdateClientSuccessResponse"
                }
              }
            },
            "description": "Client updated successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "examples": {
                  "invalid-corporate-number": {
                    "summary": "Invalid corporate number format",
                    "value": {
                      "error": "Validation Error",
                      "message": "法人番号の形式が正しくありません。13桁の数字で入力してください。",
                      "statusCode": 400
                    }
                  },
                  "validation-error": {
                    "summary": "Validation error",
                    "value": {
                      "error": "Validation Error",
                      "message": "email must be an email",
                      "statusCode": 400
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Invalid request data or validation errors"
          },
          "401": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "User not authenticated"
          },
          "404": {
            "content": {
              "application/json": {
                "examples": {
                  "client-not-found": {
                    "summary": "Client not found or not authorized",
                    "value": {
                      "error": "Not Found",
                      "message": "Client not found or you are not authorized to update this client",
                      "statusCode": 404
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Client not found or user not authorized"
          },
          "409": {
            "content": {
              "application/json": {
                "examples": {
                  "duplicate-corporate-number": {
                    "summary": "Duplicate corporate number",
                    "value": {
                      "code": "CLIENT_DUPLICATE_CORPORATE_NUMBER",
                      "error": "Conflict",
                      "message": "法人番号 1234567890123 は既に「別の株式会社」で登録されています",
                      "statusCode": 409
                    }
                  },
                  "duplicate-name": {
                    "summary": "Duplicate client name",
                    "value": {
                      "code": "CLIENT_DUPLICATE_NAME",
                      "error": "Conflict",
                      "message": "取引先名「新サンプル株式会社」は既に登録されています",
                      "statusCode": 409
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Conflict - duplicate corporate number or name"
          },
          "500": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update an existing client",
        "tags": [
          "Client"
        ]
      }
    },
    "/clients/{client_id}/documents": {
      "get": {
        "description": "Retrieves all documents linked to a specific trading partner.\n\n## Link Types Returned\n- **direct**: Linked via foreign key (sales_invoice.client_id)\n- **client_info**: Linked via JSONB `clientInfo.companyName`\n- **buyer_info**: Linked via JSONB `buyerInfo.companyName`\n- **supplier_info**: Linked via JSONB `supplierInfo.companyName`\n\n## Role Filtering\nFilter documents by the client's role in the transaction:\n- **customer**: Documents where client appears in `clientInfo` (we sell to them)\n- **supplier**: Documents where client appears in `supplierInfo` (we buy from them)\n- **both**: All documents regardless of role\n\n## Use Cases\n- View all business documents for a trading partner\n- Audit transaction history\n- Prepare for meetings with the client\n- Generate reports by trading partner",
        "parameters": [
          {
            "description": "Client UUID",
            "in": "path",
            "name": "client_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Page number",
            "in": "query",
            "name": "page_number",
            "required": false,
            "schema": {
              "default": 1,
              "minimum": 1,
              "type": "number"
            }
          },
          {
            "description": "Items per page",
            "in": "query",
            "name": "page_size",
            "required": false,
            "schema": {
              "default": 20,
              "maximum": 100,
              "minimum": 1,
              "type": "number"
            }
          },
          {
            "description": "Filter by document type",
            "in": "query",
            "name": "document_type",
            "required": false,
            "schema": {
              "enum": [
                "sales_quotation",
                "purchase_order",
                "delivery_note",
                "sales_invoice"
              ],
              "type": "string"
            }
          },
          {
            "description": "Filter by client role in transaction",
            "in": "query",
            "name": "role",
            "required": false,
            "schema": {
              "default": "both",
              "enum": [
                "customer",
                "supplier",
                "both"
              ],
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-documents": {
                    "summary": "Documents linked to trading partner",
                    "value": {
                      "data": {
                        "items": [
                          {
                            "amount": 110000,
                            "createdAt": "2026-01-10T10:30:00.000Z",
                            "documentName": "請求書_ABC株式会社_2026-01",
                            "documentType": "sales_invoice",
                            "id": "550e8400-e29b-41d4-a716-446655440000",
                            "linkType": "client_info",
                            "status": "published",
                            "updatedAt": "2026-01-10T10:30:00.000Z"
                          },
                          {
                            "amount": 100000,
                            "createdAt": "2026-01-05T09:00:00.000Z",
                            "documentName": "見積書_ABC株式会社_2026-01",
                            "documentType": "sales_quotation",
                            "id": "660f9511-f40c-52e5-b827-557766551111",
                            "linkType": "client_info",
                            "status": "published",
                            "updatedAt": "2026-01-05T09:00:00.000Z"
                          }
                        ],
                        "pagination": {
                          "currentPage": 1,
                          "hasNext": false,
                          "hasPrevious": false,
                          "pageSize": 20,
                          "totalItems": 2,
                          "totalPages": 1
                        }
                      },
                      "message": "Client documents retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ClientDocumentsResponse"
                }
              }
            },
            "description": "Client documents retrieved successfully"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Client not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get documents linked to trading partner (取引先書類)",
        "tags": [
          "Client"
        ]
      }
    },
    "/clients/{client_id}/full": {
      "get": {
        "description": "Composite endpoint for the client detail page (取引先詳細). Returns client data with optional stats and recent documents in a single parallel request instead of 3 separate calls.\n\n**Parallelizes:**\n1. Client record — `/api/clients/:client_id`\n2. Client stats (optional) — `/api/clients/:client_id/stats`\n3. Client documents (optional) — `/api/clients/:client_id/documents`\n\n**Performance:**\n| Metric | Before (waterfall) | After (parallel) |\n|--------|-------------------|-----------------|\n| Requests | 3 sequential | 1 |\n| Latency | ~600ms+ | ~200ms |\n\n**Caching:** Memory cache 3 minutes, stale-while-revalidate 90s, ETag supported.\n\n**Graceful degradation:** Stats or documents failures return null without blocking client data.",
        "operationId": "getClientFull",
        "parameters": [
          {
            "description": "Client UUID",
            "in": "path",
            "name": "client_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Include usage statistics (default true)",
            "in": "query",
            "name": "include_stats",
            "schema": {
              "default": true,
              "type": "boolean"
            }
          },
          {
            "description": "Include recent documents (default true)",
            "in": "query",
            "name": "include_documents",
            "schema": {
              "default": true,
              "type": "boolean"
            }
          },
          {
            "description": "Documents per page (default 10)",
            "in": "query",
            "name": "document_page_size",
            "schema": {
              "default": 10,
              "maximum": 100,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ClientFullResponse"
                }
              }
            },
            "description": "Client full data"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Client not found"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get client with stats and documents in one request",
        "tags": [
          "Clients"
        ]
      }
    },
    "/clients/{client_id}/stats": {
      "get": {
        "description": "Retrieves comprehensive statistics for a specific trading partner.\n\n## Document Linking Methods\nStatistics are aggregated from documents linked via:\n1. **Direct FK**: `sales_invoice.client_id`\n2. **JSONB clientInfo**: `content->'clientInfo'->>'companyName'` (quotations, invoices)\n3. **JSONB buyerInfo**: `content->'buyerInfo'->>'companyName'` (purchase orders, delivery notes)\n4. **JSONB supplierInfo**: `content->'supplierInfo'->>'companyName'` (purchase orders)\n\n## Japanese B2B Document Flow\n- **見積書** (Quotation) → linked via clientInfo\n- **発注書** (Purchase Order) → linked via buyerInfo/supplierInfo\n- **納品書** (Delivery Note) → linked via buyerInfo  \n- **請求書** (Invoice) → linked via clientInfo or direct FK\n\n## Date Filtering\nUse `start_date` and `end_date` to filter statistics by time period.",
        "parameters": [
          {
            "description": "Client UUID",
            "in": "path",
            "name": "client_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Filter start date (ISO format)",
            "in": "query",
            "name": "start_date",
            "required": false,
            "schema": {
              "example": "2026-01-01",
              "format": "date",
              "type": "string"
            }
          },
          {
            "description": "Filter end date (ISO format)",
            "in": "query",
            "name": "end_date",
            "required": false,
            "schema": {
              "example": "2026-12-31",
              "format": "date",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-stats": {
                    "summary": "Trading partner with active relationship",
                    "value": {
                      "data": {
                        "deliveryNoteCount": 5,
                        "documentCount": 33,
                        "documentsByType": [
                          {
                            "count": 15,
                            "type": "sales_invoice"
                          },
                          {
                            "count": 8,
                            "type": "sales_quotation"
                          },
                          {
                            "count": 5,
                            "type": "purchase_order"
                          },
                          {
                            "count": 5,
                            "type": "delivery_note"
                          }
                        ],
                        "invoiceCount": 15,
                        "lastActivityDate": "2026-01-10T10:30:00.000Z",
                        "purchaseOrderCount": 5,
                        "quotationCount": 8,
                        "totalInvoiceAmount": 1500000,
                        "totalQuotationAmount": 2000000
                      },
                      "message": "Client statistics retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ClientStatsResponse"
                }
              }
            },
            "description": "Client statistics retrieved successfully"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Client not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get trading partner statistics (取引先統計)",
        "tags": [
          "Client"
        ]
      }
    },
    "/companies": {
      "get": {
        "description": "Retrieve all companies owned by the authenticated user.\n\n## Company Listing\nReturns comprehensive company information including:\n- **Basic Information**: Company name, capital, representative details\n- **Legal Details**: Corporate number, fiscal year information\n- **Registration Status**: Invoice registration and qualification status\n- **Setup Status**: Company setup completion tracking\n- **Document Links**: Associated Teikan documents and legal filings\n\n## Company Information\n- **Japanese Format**: All information formatted for Japanese business requirements\n- **Legal Compliance**: Includes all legally required company information\n- **Registration Tracking**: Invoice registration system compliance status\n- **Setup Workflow**: Track company setup completion status\n- **Document Integration**: Links to associated legal documents\n\n## Use Cases\n- **Dashboard Display**: Show user's companies in business dashboard\n- **Company Selection**: Allow users to select active company for operations\n- **Status Monitoring**: Monitor setup completion and compliance status\n- **Legal Overview**: Review legal registration and compliance information\n- **Business Management**: Manage multiple business entities\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CompanyListResponse"
                }
              }
            },
            "description": "Companies retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List user companies",
        "tags": [
          "Company Management"
        ]
      },
      "put": {
        "description": "Update company information with Japanese business validation and legal compliance checking.\n\n## Company Update Process\nComprehensive update with validation:\n- **Business Information**: Update name, capital, representative details\n- **Legal Information**: Corporate number validation and fiscal year management\n- **Address Management**: Japanese address format validation\n- **Document Integration**: Link to updated Teikan documents\n- **Compliance Validation**: Ensure all updates meet legal requirements\n\n## Japanese Business Validation\n- **Corporate Number**: 13-digit format validation per Japanese law\n- **Fiscal Year**: MMDD format validation for Japanese business calendar\n- **Address Format**: Japanese address format validation\n- **Name Requirements**: Japanese company name format validation\n- **Capital Requirements**: Minimum capital requirements validation\n\n## Legal Compliance\n- **Corporate Law**: Updates comply with Japanese corporate law\n- **Registration Requirements**: Maintain legal registration compliance\n- **Invoice System**: Qualified invoice issuer requirements\n- **Documentation**: Maintain proper legal documentation\n- **Audit Trail**: Complete update history for legal compliance\n\n## Update Validation\n- **Required Fields**: Validate all legally required information\n- **Format Validation**: Ensure Japanese business format compliance\n- **Duplicate Prevention**: Prevent duplicate corporate numbers\n- **Consistency Checks**: Ensure fiscal year consistency\n- **Legal Requirements**: Meet all Japanese corporate law requirements\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "basic_update": {
                  "summary": "Basic information update",
                  "value": {
                    "name": "株式会社ソロボス",
                    "office_address": "東京都渋谷区渋谷1-1-1",
                    "representative": "田中太郎"
                  }
                },
                "complete_update": {
                  "summary": "Complete company information update",
                  "value": {
                    "capital": 1000000,
                    "corporate_number": "1234567890123",
                    "fiscal_year_end": 331,
                    "fiscal_year_start": 401,
                    "linked_document_id": "456e7890-f12a-34b5-c678-901234567890",
                    "name": "株式会社ソロボス",
                    "office_address": "東京都渋谷区渋谷1-1-1 ソロボスビル3F",
                    "representative": "田中太郎"
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/UpdateCompanyRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CompanyResponse"
                }
              }
            },
            "description": "Company updated successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Invalid corporate number format",
                      "type": "string"
                    },
                    "fieldErrors": {
                      "additionalProperties": {
                        "items": {
                          "type": "string"
                        },
                        "type": "array"
                      },
                      "example": {
                        "corporate_number": [
                          "Corporate number must be 13 digits"
                        ],
                        "fiscal_year_start": [
                          "Fiscal year start must be in MMDD format"
                        ]
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid company data or validation errors"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Company not found or access denied",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Company not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update company information",
        "tags": [
          "Company Management"
        ]
      }
    },
    "/companies/available-teikan": {
      "get": {
        "description": "Retrieve available Teikan (定款) documents that can be used for company setup and information extraction.\n\n## Teikan Document Management\nReturns available documents with:\n- **Document Listing**: All available Teikan documents for the user\n- **Document Status**: Published documents ready for company setup\n- **Integration Ready**: Documents that can be used for AI extraction\n- **Setup Support**: Documents suitable for automated company setup\n- **Legal Compliance**: Properly formatted legal documents\n\n## Teikan Document Features\n- **Legal Documents**: Authentic Teikan documents for company setup\n- **AI Integration**: Documents suitable for automated information extraction\n- **Setup Automation**: Enable automated company setup from legal documents\n- **Compliance Support**: Ensure legal compliance during company registration\n- **Document Validation**: Only properly formatted and validated documents\n\n## Use Cases\n- **Company Setup**: Select Teikan document for automated company setup\n- **Document Selection**: Choose appropriate legal document for business registration\n- **AI Extraction**: Identify documents suitable for automated information extraction\n- **Legal Compliance**: Ensure proper legal documentation for company registration\n- **Setup Workflow**: Support automated company setup workflows\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "available_documents": {
                    "summary": "Available Teikan documents",
                    "value": {
                      "data": [
                        {
                          "created_at": "2024-01-15T10:30:00.000Z",
                          "document_type": "teikan",
                          "id": "456e7890-f12a-34b5-c678-901234567890",
                          "status": "published",
                          "title": "株式会社ソロボス 定款"
                        },
                        {
                          "created_at": "2024-01-10T09:15:00.000Z",
                          "document_type": "teikan",
                          "id": "789e0123-e45b-67c8-d901-234567890123",
                          "status": "published",
                          "title": "合同会社テスト 定款"
                        }
                      ],
                      "message": "Available Teikan documents retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/TeikanDocumentListResponse"
                }
              }
            },
            "description": "Available Teikan documents retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get available Teikan documents",
        "tags": [
          "Company Management"
        ]
      }
    },
    "/companies/extract/{document_id}": {
      "post": {
        "description": "Extract company information from Teikan (定款) document using AI analysis without updating company records.\n\n## AI Information Extraction\nAdvanced document analysis with:\n- **Document Processing**: AI-powered analysis of Teikan document content\n- **Information Identification**: Identify and extract key company information\n- **Data Structuring**: Structure extracted information in standardized format\n- **Validation Checks**: Validate extracted information for completeness and accuracy\n- **Preview Mode**: Extract information without updating company records\n\n## Extraction Output\nReturns structured company information:\n- **Company Name**: Official company name from legal document\n- **Capital Details**: Company capital amount and currency\n- **Representative Information**: Representative director name and details\n- **Address Information**: Office address in Japanese format\n- **Fiscal Year Information**: Fiscal year start and end dates\n- **Legal Structure**: Corporate structure and legal entity type\n\n## Use Cases\n- **Information Preview**: Preview extracted information before applying updates\n- **Data Validation**: Validate document content before company setup\n- **Document Analysis**: Analyze Teikan document content and structure\n- **Setup Planning**: Plan company setup based on extracted information\n- **Legal Review**: Review extracted legal information for accuracy\n\n## AI Processing\n- **Natural Language Processing**: Advanced NLP for Japanese legal document analysis\n- **Pattern Recognition**: Identify standard Teikan document patterns and structures\n- **Information Validation**: Validate extracted information against legal requirements\n- **Error Detection**: Identify potential extraction errors or ambiguities\n- **Quality Assurance**: Ensure high-quality extraction results\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "ID of the Teikan document to extract information from",
            "example": "456e7890-f12a-34b5-c678-901234567890",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "extracted_info": {
                    "summary": "Extracted company information",
                    "value": {
                      "data": {
                        "capital": 1000000,
                        "companyName": "株式会社ソロボス",
                        "fiscalYearEnd": 331,
                        "fiscalYearStart": 401,
                        "officeAddress": "東京都渋谷区渋谷1-1-1 ソロボスビル3F",
                        "representative": "田中太郎"
                      },
                      "message": "Company information extracted successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ExtractedCompanyInfoResponse"
                }
              }
            },
            "description": "Company information extracted successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Document is not suitable for company information extraction",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid document or unsuitable for extraction"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Teikan document not found or access denied",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Document not found or access denied"
          },
          "422": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "details": {
                      "properties": {
                        "documentAnalysis": {
                          "properties": {
                            "contentQuality": {
                              "example": "low",
                              "type": "string"
                            },
                            "documentType": {
                              "example": "teikan",
                              "type": "string"
                            },
                            "extractableFields": {
                              "example": [
                                "companyName",
                                "representative"
                              ],
                              "items": {
                                "type": "string"
                              },
                              "type": "array"
                            }
                          },
                          "type": "object"
                        },
                        "extractionErrors": {
                          "example": [
                            "Document content insufficient for extraction",
                            "Company information not clearly identifiable"
                          ],
                          "items": {
                            "type": "string"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "error": {
                      "example": "Unable to extract company information from document",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "AI extraction failed or insufficient document content"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Extract company information from Teikan document",
        "tags": [
          "Company Management"
        ]
      }
    },
    "/companies/me": {
      "get": {
        "description": "Retrieve the current user's primary company with complete business and legal information.\n\n## Primary Company Retrieval\nReturns the user's main company with:\n- **Complete Business Profile**: All company information and legal details\n- **Registration Status**: Current invoice registration and qualification status\n- **Setup Progress**: Company setup completion status and requirements\n- **Legal Compliance**: Corporate number, fiscal year, and legal registration details\n- **Document Integration**: Associated Teikan documents and legal filings\n\n## Company Information Includes\n- **Basic Details**: Company name, capital, representative information\n- **Legal Information**: Corporate number, fiscal year dates, registration details\n- **Compliance Status**: Invoice registration system qualification and verification\n- **Setup Status**: Whether company setup is completed and business-ready\n- **Address Information**: Office address in Japanese format\n- **Document Links**: Associated legal documents and Teikan filings\n\n## Use Cases\n- **User Dashboard**: Display primary company information\n- **Business Operations**: Get company context for business operations\n- **Legal Compliance**: Access legal registration and compliance information\n- **Setup Validation**: Check if company setup is complete\n- **Document Management**: Access associated legal documents\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "complete_company": {
                    "summary": "Complete company information",
                    "value": {
                      "data": {
                        "capital": 1000000,
                        "corporate_number": "1234567890123",
                        "created_at": "2024-01-15T10:30:00.000Z",
                        "deleted_at": null,
                        "fiscal_year_end": 331,
                        "fiscal_year_start": 401,
                        "id": "123e4567-e89b-12d3-a456-426614174000",
                        "invoice_registration_date": "2023-10-01T00:00:00.000Z",
                        "invoice_registration_number": "T1234567890123",
                        "invoice_registration_verified": true,
                        "invoice_registration_verified_at": "2023-10-01T10:30:00.000Z",
                        "is_deleted": false,
                        "is_multiple_workplace_employee": false,
                        "is_qualified_invoice_issuer": true,
                        "linked_document_id": "456e7890-f12a-34b5-c678-901234567890",
                        "name": "株式会社ソロボス",
                        "office_address": "東京都渋谷区渋谷1-1-1 ソロボスビル3F",
                        "owner_id": "abc12345-def6-7890-ghij-klmnopqrstuv",
                        "representative": "田中太郎",
                        "setup_completed": true,
                        "updated_at": "2024-01-15T10:30:00.000Z"
                      },
                      "message": "Company retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/CompanyResponse"
                }
              }
            },
            "description": "User company retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "example": null,
                      "type": "null"
                    },
                    "message": {
                      "example": "No company found for user",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 404,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "No company found for user"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get current user company",
        "tags": [
          "Company Management"
        ]
      }
    },
    "/companies/populate/{document_id}": {
      "post": {
        "description": "Automatically populate company information using AI extraction from Teikan (定款) document.\n\n## AI-Powered Company Setup\nIntelligent document processing with:\n- **Document Analysis**: AI-powered analysis of Teikan document content\n- **Information Extraction**: Automatic extraction of company details from legal text\n- **Data Validation**: Validation of extracted information for accuracy\n- **Company Population**: Automatic population of company fields with extracted data\n- **Legal Compliance**: Ensure extracted information meets legal requirements\n\n## Extraction Capabilities\n- **Company Name**: Extract official company name from legal documents\n- **Capital Information**: Extract capital amount and financial details\n- **Representative Details**: Extract representative director information\n- **Address Information**: Extract office address in proper Japanese format\n- **Fiscal Year**: Extract fiscal year start and end dates\n- **Legal Details**: Extract corporate structure and legal information\n\n## Processing Options\n- **Force Update**: Option to force update existing company information\n- **Selective Update**: Update only missing or empty fields\n- **Validation Checks**: Comprehensive validation of extracted information\n- **Error Handling**: Detailed error reporting for extraction issues\n- **Audit Trail**: Complete logging of extraction and update process\n\n## Use Cases\n- **Automated Setup**: Streamline company setup process with document automation\n- **Data Accuracy**: Ensure accurate company information from legal documents\n- **Time Efficiency**: Reduce manual data entry time and errors\n- **Legal Compliance**: Maintain consistency with legal documentation\n- **Business Automation**: Enable automated business registration workflows\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "ID of the Teikan document to extract information from",
            "example": "456e7890-f12a-34b5-c678-901234567890",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "Whether to force update existing company information",
            "example": false,
            "in": "query",
            "name": "force_update",
            "required": false,
            "schema": {
              "default": false,
              "type": "boolean"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CompanyResponse"
                }
              }
            },
            "description": "Company populated successfully from Teikan document"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Document is not suitable for company information extraction",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid document or extraction errors"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Teikan document not found or access denied",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Document not found or access denied"
          },
          "422": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "details": {
                      "properties": {
                        "extractionErrors": {
                          "example": [
                            "Company name not found in document",
                            "Capital amount unclear or missing"
                          ],
                          "items": {
                            "type": "string"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "error": {
                      "example": "Unable to extract company information from document",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "AI extraction failed or insufficient document content"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Populate company from Teikan document",
        "tags": [
          "Company Management"
        ]
      }
    },
    "/companies/{company_id}": {
      "get": {
        "description": "Retrieve specific company information by company ID with complete business and legal details.\n\n## Company Retrieval by ID\nReturns comprehensive company information including:\n- **Complete Business Profile**: All company information and legal details\n- **Legal Compliance**: Corporate registration and compliance status\n- **Financial Information**: Capital, fiscal year, and financial details\n- **Registration Details**: Invoice registration and qualification status\n- **Document Integration**: Associated legal documents and filings\n\n## Access Control\n- **Owner Verification**: Only company owner can access company details\n- **Data Security**: Secure access to sensitive business information\n- **Legal Protection**: Protect confidential business and legal information\n- **Audit Trail**: Complete access logging for security and compliance\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the company to retrieve",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "in": "path",
            "name": "company_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CompanyResponse"
                }
              }
            },
            "description": "Company retrieved successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Invalid company ID format",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid company ID format"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Company not found or access denied",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Company not found or access denied"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get company by ID",
        "tags": [
          "Company Management"
        ]
      }
    },
    "/companies/{company_id}/complete-setup": {
      "post": {
        "description": "Mark company setup as completed after validating all required information and legal compliance.\n\n## Setup Completion Process\nComprehensive validation and completion:\n- **Information Validation**: Verify all required company information is complete\n- **Legal Compliance**: Ensure all legal requirements are met\n- **Registration Verification**: Validate corporate registration details\n- **Document Verification**: Confirm all required documents are in place\n- **Business Readiness**: Ensure company is ready for business operations\n\n## Setup Requirements\n- **Basic Information**: Company name, representative, address must be complete\n- **Legal Details**: Corporate number and fiscal year must be properly set\n- **Document Integration**: Teikan document must be properly linked\n- **Compliance Status**: All legal compliance requirements must be met\n- **Registration Status**: Corporate registration must be verified\n\n## Post-Completion Benefits\n- **Business Operations**: Enable full business operations and features\n- **Legal Compliance**: Maintain proper legal standing and compliance\n- **System Access**: Unlock advanced system features and capabilities\n- **Audit Readiness**: Ensure company is ready for legal and financial audits\n- **Business Growth**: Enable business growth and expansion capabilities\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the company to complete setup for",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "in": "path",
            "name": "company_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CompanySetupResponse"
                }
              }
            },
            "description": "Company setup completed successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Company setup requirements not met",
                      "type": "string"
                    },
                    "missingRequirements": {
                      "example": [
                        "Corporate number required",
                        "Fiscal year dates required",
                        "Representative name required"
                      ],
                      "items": {
                        "type": "string"
                      },
                      "type": "array"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Setup requirements not met or validation errors"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Company not found or access denied",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Company not found or access denied"
          },
          "409": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Company setup is already completed",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Company setup already completed"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Complete company setup",
        "tags": [
          "Company Management"
        ]
      }
    },
    "/company-context": {
      "get": {
        "description": "会社情報・税務設定・有効な契約・主要取引先・未解決論点・証憑統計を1回の読み取りで返します。`format=markdown` を指定すると、LLMのシステムプロンプトに前置きするための日本語ブリーフィングを返します。",
        "parameters": [
          {
            "in": "query",
            "name": "format",
            "schema": {
              "default": "json",
              "enum": [
                "json",
                "markdown"
              ],
              "type": "string"
            }
          },
          {
            "description": "期間終了済みの契約も含める（過年度の説明に使用）",
            "in": "query",
            "name": "includeExpiredAgreements",
            "schema": {
              "default": false,
              "type": "boolean"
            }
          },
          {
            "in": "query",
            "name": "counterpartyLimit",
            "schema": {
              "default": 15,
              "maximum": 100,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "oneOf": [
                        {
                          "$ref": "#/components/schemas/CompanyContext"
                        },
                        {
                          "$ref": "#/components/schemas/CompanyContextBriefing"
                        }
                      ]
                    },
                    "message": {
                      "type": "string"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "会社コンテキスト"
          },
          "401": {
            "description": "未認証"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "会社コンテキストを取得",
        "tags": [
          "Company Context"
        ]
      }
    },
    "/company-context/open-questions": {
      "get": {
        "parameters": [
          {
            "description": "カンマ区切り: open,answered,confirmed,superseded,dismissed",
            "in": "query",
            "name": "status",
            "schema": {
              "type": "string"
            }
          },
          {
            "example": "consumption_tax",
            "in": "query",
            "name": "domain",
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "指定すると、その依頼の確認事項管理表に載せた論点だけを No. 順で返す",
            "in": "query",
            "name": "engagementId",
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "items": {
                          "items": {
                            "$ref": "#/components/schemas/OpenQuestion"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "未解決論点"
          },
          "401": {
            "description": "未認証"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "未解決論点の一覧",
        "tags": [
          "Company Context"
        ]
      },
      "post": {
        "description": "税理士等への確認事項を登録します。`questionKey` は `owner:` で始まる必要があり、システムが提起した論点は書き換えられません。省略すると新しいキーを発行します。同じキーで再送すると、確定済みでない限り内容を更新します（再読込で重複しません）。",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "detail": {
                    "maxLength": 8000,
                    "type": "string"
                  },
                  "domain": {
                    "maxLength": 64,
                    "nullable": true,
                    "type": "string"
                  },
                  "engagementId": {
                    "format": "uuid",
                    "nullable": true,
                    "type": "string"
                  },
                  "questionKey": {
                    "description": "owner: で始まるキー（省略可）",
                    "maxLength": 200,
                    "type": "string"
                  },
                  "reviewBy": {
                    "description": "判断の期限。blocking の確認事項に付けると申告カレンダーの「判断が必要なこと」に出ます。",
                    "format": "date",
                    "nullable": true,
                    "type": "string"
                  },
                  "severity": {
                    "enum": [
                      "blocking",
                      "material",
                      "advisory"
                    ],
                    "type": "string"
                  },
                  "sortOrder": {
                    "maximum": 9999,
                    "minimum": 1,
                    "nullable": true,
                    "type": "integer"
                  },
                  "title": {
                    "maxLength": 300,
                    "minLength": 1,
                    "type": "string"
                  }
                },
                "required": [
                  "title"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "created": {
                          "type": "boolean"
                        },
                        "id": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "questionKey": {
                          "type": "string"
                        }
                      },
                      "required": [
                        "id",
                        "questionKey",
                        "created"
                      ],
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "登録した確認事項（201 = 新規、200 = 同じキーの更新）"
          },
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "created": {
                          "type": "boolean"
                        },
                        "id": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "questionKey": {
                          "type": "string"
                        }
                      },
                      "required": [
                        "id",
                        "questionKey",
                        "created"
                      ],
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "登録した確認事項（201 = 新規、200 = 同じキーの更新）"
          },
          "400": {
            "description": "入力不正"
          },
          "401": {
            "description": "未認証"
          },
          "404": {
            "description": "依頼（engagementId）が存在しない、または自分のものではない"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "確認事項を追加する（同じキーなら更新）",
        "tags": [
          "Company Context"
        ]
      }
    },
    "/company-context/open-questions/answers": {
      "get": {
        "description": "税理士がやり取りまたは最終結論で回答した確認事項と、その証憑リンク。仕訳・固定資産の横に「税理士の回答あり」を表示するために使います（BE ADR-0031）。",
        "parameters": [
          {
            "in": "query",
            "name": "fiscalYear",
            "schema": {
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "items": {
                          "items": {
                            "$ref": "#/components/schemas/OpenQuestionProfessionalAnswer"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "回答一覧"
          },
          "401": {
            "description": "未認証"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "税理士の回答一覧（関わる仕訳・固定資産つき）",
        "tags": [
          "Company Context"
        ]
      }
    },
    "/company-context/open-questions/export": {
      "get": {
        "description": "No. / 確認事項 / 税理士からのご質問 n / 回答 n / 最終結論 / 状況 の表を .xlsx または .docx で返します。`engagementId` を指定すると、その依頼の管理表だけを No. 順で出力します。",
        "parameters": [
          {
            "in": "query",
            "name": "format",
            "schema": {
              "default": "xlsx",
              "enum": [
                "xlsx",
                "docx"
              ],
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "engagementId",
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "カンマ区切り: open,answered,confirmed,superseded,dismissed",
            "in": "query",
            "name": "status",
            "schema": {
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "domain",
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": {
                "schema": {
                  "format": "binary",
                  "type": "string"
                }
              },
              "application/vnd.openxmlformats-officedocument.wordprocessingml.document": {
                "schema": {
                  "format": "binary",
                  "type": "string"
                }
              }
            },
            "description": "確認事項管理表のファイル"
          },
          "400": {
            "description": "入力不正"
          },
          "401": {
            "description": "未認証"
          },
          "404": {
            "description": "依頼（engagementId）が存在しない、または自分のものではない"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "確認事項管理表をダウンロードする（Excel / Word）",
        "tags": [
          "Company Context"
        ]
      }
    },
    "/company-context/open-questions/import/apply": {
      "post": {
        "description": "プレビューと同じファイル（file_hash で確認）を取り込みます。やり取りは追記のみ、最終結論は税理士の回答（answeredBy=税理士・confirmedByProfessional）として記録。記録済みと違う最終結論は overwrite_rows に指定した行だけ上書きします。対応する確認事項がない行は新しい確認事項として登録します。",
        "requestBody": {
          "content": {
            "multipart/form-data": {
              "schema": {
                "properties": {
                  "engagement_id": {
                    "format": "uuid",
                    "type": "string"
                  },
                  "file": {
                    "format": "binary",
                    "type": "string"
                  },
                  "file_hash": {
                    "pattern": "^[0-9a-f]{64}$",
                    "type": "string"
                  },
                  "overwrite_rows": {
                    "description": "上書きを確認した行番号（カンマ区切り）",
                    "type": "string"
                  },
                  "promote_rows": {
                    "description": "税理士の回答を最終結論として記録する行番号（カンマ区切り）",
                    "type": "string"
                  }
                },
                "required": [
                  "file",
                  "engagement_id",
                  "file_hash"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "conclusionsRecorded": {
                          "type": "integer"
                        },
                        "created": {
                          "type": "integer"
                        },
                        "evidenceLinked": {
                          "type": "integer"
                        },
                        "roundsAdded": {
                          "type": "integer"
                        },
                        "skippedConflicts": {
                          "type": "integer"
                        },
                        "updated": {
                          "type": "integer"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "取込結果"
          },
          "400": {
            "description": "入力不正"
          },
          "401": {
            "description": "未認証"
          },
          "404": {
            "description": "依頼（engagement_id）が存在しない、または自分のものではない"
          },
          "409": {
            "description": "プレビューしたファイルと内容が違う"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "確認事項管理表（.xlsx）を取り込む",
        "tags": [
          "Company Context"
        ]
      }
    },
    "/company-context/open-questions/import/preview": {
      "post": {
        "description": "税理士が記入した管理表を読み、各行を依頼の確認事項に No.（件名で照合）→件名の順で対応づけ、追加されるやり取り・最終結論・新規の確認事項を返します。書き込みはしません。",
        "requestBody": {
          "content": {
            "multipart/form-data": {
              "schema": {
                "properties": {
                  "engagement_id": {
                    "format": "uuid",
                    "type": "string"
                  },
                  "file": {
                    "format": "binary",
                    "type": "string"
                  },
                  "promote_rows": {
                    "description": "税理士の回答を最終結論として扱う行番号（カンマ区切り）",
                    "type": "string"
                  }
                },
                "required": [
                  "file",
                  "engagement_id"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/OpenQuestionImportPreview"
                    },
                    "message": {
                      "type": "string"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "プレビュー"
          },
          "400": {
            "description": "入力不正"
          },
          "401": {
            "description": "未認証"
          },
          "404": {
            "description": "依頼（engagement_id）が存在しない、または自分のものではない"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "確認事項管理表（.xlsx）の取込プレビュー",
        "tags": [
          "Company Context"
        ]
      }
    },
    "/company-context/open-questions/{question_key}/answer": {
      "post": {
        "description": "`confirmedByProfessional: true` を指定すると自動検出による上書きが止まり、論点は再提起されません。confirmed / dismissed で論点を閉じる回答は、決算確定の確認（BE ADR-0031）を解除するため8文字以上が必要です。confirmedByProfessional: true は受け付けません（税理士の回答は確認事項管理表の取込で記録）。PREPAID_INPUT_CREDIT 等の重大な指摘は当社の回答では閉じられません。",
        "parameters": [
          {
            "in": "path",
            "name": "question_key",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "answer": {
                    "maxLength": 4000,
                    "type": "string"
                  },
                  "confirmedByProfessional": {
                    "default": false,
                    "type": "boolean"
                  },
                  "positionBasis": {
                    "maxLength": 2000,
                    "nullable": true,
                    "type": "string"
                  },
                  "reviewBy": {
                    "format": "date",
                    "nullable": true,
                    "type": "string"
                  },
                  "status": {
                    "enum": [
                      "answered",
                      "confirmed",
                      "dismissed"
                    ],
                    "type": "string"
                  },
                  "workingPosition": {
                    "maxLength": 2000,
                    "nullable": true,
                    "type": "string"
                  }
                },
                "required": [
                  "answer"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "id": {
                          "format": "uuid",
                          "type": "string"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "回答を記録"
          },
          "401": {
            "description": "未認証"
          },
          "404": {
            "description": "該当する論点が存在しない"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "未解決論点に回答する",
        "tags": [
          "Company Context"
        ]
      }
    },
    "/company-context/open-questions/{question_key}/exchanges": {
      "post": {
        "description": "税理士からの質問（author=professional）または当社の回答（author=company）を追記します。編集・削除はできません。",
        "parameters": [
          {
            "in": "path",
            "name": "question_key",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "author": {
                    "enum": [
                      "professional",
                      "company"
                    ],
                    "type": "string"
                  },
                  "body": {
                    "maxLength": 8000,
                    "minLength": 1,
                    "type": "string"
                  }
                },
                "required": [
                  "author",
                  "body"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "exchanges": {
                          "items": {
                            "$ref": "#/components/schemas/OpenQuestionExchange"
                          },
                          "type": "array"
                        },
                        "id": {
                          "format": "uuid",
                          "type": "string"
                        }
                      },
                      "required": [
                        "id",
                        "exchanges"
                      ],
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "追記後のやり取り"
          },
          "400": {
            "description": "入力不正"
          },
          "401": {
            "description": "未認証"
          },
          "404": {
            "description": "該当する論点が存在しない"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "確認事項にやり取りを1件追記する",
        "tags": [
          "Company Context"
        ]
      }
    },
    "/company-events": {
      "get": {
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "events": {
                          "items": {
                            "$ref": "#/components/schemas/CompanyEvent"
                          },
                          "type": "array"
                        },
                        "kinds": {
                          "items": {
                            "$ref": "#/components/schemas/CompanyEventKind"
                          },
                          "type": "array"
                        }
                      },
                      "required": [
                        "kinds",
                        "events"
                      ],
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Kinds and events"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "What can be recorded, and the recorded events with the 届出 rows each one started",
        "tags": [
          "Company events"
        ]
      },
      "post": {
        "description": "The engine derives the 届出 rows (変更登記 2週間, 異動届 10日, 年金 5日, 変更登録 15日 …) from the event date. A row whose window had already closed when the event was recorded says so (inputs.recordedAfterDue).",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateCompanyEventRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/CompanyEvent"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Recorded"
          },
          "400": {
            "description": "Validation error (RFC 9457)"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Record an event; the deadlines are recomputed before the response",
        "tags": [
          "Company events"
        ]
      }
    },
    "/company-events/{id}": {
      "delete": {
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "id": {
                          "format": "uuid",
                          "type": "string"
                        }
                      },
                      "required": [
                        "id"
                      ],
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Removed"
          },
          "400": {
            "description": "Invalid id (RFC 9457)"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Remove an event; its open 届出 rows close on the recompute",
        "tags": [
          "Company events"
        ]
      }
    },
    "/compliance/anomaly/detect": {
      "post": {
        "description": "Analyze company financial data to detect potential anomalies and suspicious patterns using machine learning algorithms.\n      \n## Anomaly Detection Capabilities\n- **Pattern Recognition**: Advanced ML algorithms for anomaly detection\n- **Financial Analysis**: Specialized models for financial data patterns\n- **Risk Assessment**: Automated risk scoring and classification\n- **Trend Analysis**: Historical pattern comparison and deviation detection\n\n## Detection Methods\n- **Statistical Analysis**: Statistical deviation from normal patterns\n- **Machine Learning**: AI-powered anomaly detection models\n- **Rule-based Checks**: Compliance rule violation detection\n- **Comparative Analysis**: Peer comparison and industry benchmarking\n\n## Compliance Applications\n- **Fraud Detection**: Identify potentially fraudulent transactions\n- **Risk Management**: Early warning system for financial risks\n- **Audit Support**: Automated anomaly flagging for auditors\n- **Regulatory Compliance**: Ensure compliance with financial regulations\n\n## Security and Privacy\n- **Data Protection**: Secure processing of sensitive financial data\n- **Audit Logging**: Complete audit trail of all anomaly detections\n- **Access Control**: Role-based access to anomaly detection results\n- **Confidentiality**: Encrypted storage and transmission of results",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "anomaly-detection": {
                  "summary": "Financial anomaly detection request",
                  "value": {
                    "company_id": "comp_123456",
                    "end_date": "2024-01-31",
                    "start_date": "2024-01-01"
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/AnomalyDetectionRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "anomalies-detected": {
                    "summary": "Anomalies detected in financial data",
                    "value": {
                      "data": {
                        "analysis_period": {
                          "end_date": "2024-01-31",
                          "start_date": "2024-01-01"
                        },
                        "anomalies": [
                          {
                            "anomaly_id": "anom_123456",
                            "confidence_score": 0.95,
                            "description": "Unusually large transaction detected",
                            "detected_at": "2024-01-15T10:30:00.000Z",
                            "severity": "high",
                            "type": "unusual_transaction"
                          }
                        ],
                        "total_anomalies": 1
                      },
                      "message": "Anomaly detection completed successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/AnomalyDetectionResponse"
                }
              }
            },
            "description": "Anomaly detection completed successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Detect financial anomalies in company data",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/anomaly/status": {
      "get": {
        "description": "Check the status and availability of the anomaly detection service.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HealthStatusResponse"
                }
              }
            },
            "description": "Anomaly detection service status retrieved"
          }
        },
        "summary": "Check anomaly detection service status",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/corporate-number/cache/clear": {
      "post": {
        "description": "Clear the cache for corporate number data.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "example": "Corporate number cache has been cleared",
                      "type": "string"
                    },
                    "message": {
                      "example": "Cache cleared successfully",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Cache cleared successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Clear corporate number cache",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/corporate-number/lookup": {
      "get": {
        "description": "Retrieve detailed corporate information using a 13-digit corporate number from the NTA database.\n      \n## Corporate Number System\n- **Unique Identification**: Each corporation has a unique 13-digit number\n- **Official Registry**: Data sourced from National Tax Agency official records\n- **Real-time Data**: Live access to current corporate information\n- **Historical Tracking**: Optional access to historical corporate data\n\n## Information Retrieved\n- **Basic Details**: Company name, address, registration dates\n- **Status Information**: Current registration status and validity\n- **Contact Information**: Official registered address and location\n- **Registration History**: Changes and updates to corporate information\n\n## Compliance Applications\n- **Due Diligence**: Verify corporate partners and suppliers\n- **Risk Assessment**: Validate corporate legitimacy and status\n- **Contract Verification**: Confirm corporate details for agreements\n- **Audit Support**: Gather official corporate information for audits",
        "parameters": [
          {
            "description": "13-digit corporate number",
            "example": "1234567890123",
            "in": "query",
            "name": "corporate_number",
            "required": true,
            "schema": {
              "pattern": "^\\d{13}$",
              "type": "string"
            }
          },
          {
            "description": "Include historical corporate data",
            "in": "query",
            "name": "include_history",
            "required": false,
            "schema": {
              "default": false,
              "type": "boolean"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CorporateNumberResponse"
                }
              }
            },
            "description": "Corporate information retrieved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "429": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Rate limit exceeded"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Look up corporate information by corporate number",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/corporate-number/lookup-bulk": {
      "post": {
        "description": "Look up multiple corporate numbers in a single request (max 10).",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CorporateNumberBulkLookupRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "results": {
                          "items": {
                            "$ref": "#/components/schemas/CorporateNumberDetail"
                          },
                          "type": "array"
                        },
                        "summary": {
                          "properties": {
                            "found": {
                              "example": 8,
                              "type": "integer"
                            },
                            "not_found": {
                              "example": 2,
                              "type": "integer"
                            },
                            "total": {
                              "example": 10,
                              "type": "integer"
                            }
                          },
                          "type": "object"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Bulk corporate lookup completed",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Bulk corporate lookup completed"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Bulk lookup corporate numbers",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/corporate-number/search": {
      "get": {
        "description": "Search for corporations using company name with optional prefecture filter.",
        "parameters": [
          {
            "description": "Company name to search (minimum 2 characters)",
            "example": "株式会社サンプル",
            "in": "query",
            "name": "name",
            "required": true,
            "schema": {
              "minLength": 2,
              "type": "string"
            }
          },
          {
            "description": "Prefecture to filter results",
            "example": "東京都",
            "in": "query",
            "name": "prefecture",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "Maximum number of results",
            "in": "query",
            "name": "limit",
            "required": false,
            "schema": {
              "default": 10,
              "maximum": 100,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "results": {
                          "items": {
                            "$ref": "#/components/schemas/CorporateNumberDetail"
                          },
                          "type": "array"
                        },
                        "total_count": {
                          "example": 25,
                          "type": "integer"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Corporate search completed",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Corporate search completed"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Search corporations by name",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/corporate-number/status": {
      "get": {
        "description": "Check the status and availability of the NTA corporate number service.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HealthStatusResponse"
                }
              }
            },
            "description": "Corporate number service status retrieved"
          }
        },
        "summary": "Check corporate number service status",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/corporate-number/updates": {
      "get": {
        "description": "Retrieve corporate number updates within a date range.",
        "parameters": [
          {
            "description": "Start date (YYYY-MM-DD)",
            "example": "2024-01-01",
            "in": "query",
            "name": "from",
            "required": true,
            "schema": {
              "format": "date",
              "type": "string"
            }
          },
          {
            "description": "End date (YYYY-MM-DD)",
            "example": "2024-01-31",
            "in": "query",
            "name": "to",
            "required": true,
            "schema": {
              "format": "date",
              "type": "string"
            }
          },
          {
            "description": "Prefecture filter",
            "example": "東京都",
            "in": "query",
            "name": "prefecture",
            "required": false,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "period": {
                          "properties": {
                            "from": {
                              "example": "2024-01-01",
                              "format": "date",
                              "type": "string"
                            },
                            "to": {
                              "example": "2024-01-31",
                              "format": "date",
                              "type": "string"
                            }
                          },
                          "type": "object"
                        },
                        "updates": {
                          "items": {
                            "properties": {
                              "corporate_number": {
                                "example": "1234567890123",
                                "type": "string"
                              },
                              "new_value": {
                                "example": "New address",
                                "type": "string"
                              },
                              "previous_value": {
                                "example": "Old address",
                                "type": "string"
                              },
                              "update_date": {
                                "example": "2024-01-15",
                                "format": "date",
                                "type": "string"
                              },
                              "update_type": {
                                "example": "address_change",
                                "type": "string"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Corporate updates retrieved",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Corporate updates retrieved"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get corporate number updates",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/eltax/download-local-tax-xml/{sessionId}": {
      "get": {
        "parameters": [
          {
            "in": "path",
            "name": "sessionId",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/xml": {
                "schema": {
                  "format": "binary",
                  "type": "string"
                }
              }
            },
            "description": "XML download"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Download eLTAX local tax XML",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/eltax/download-municipal-tax-xml/{sessionId}": {
      "get": {
        "parameters": [
          {
            "in": "path",
            "name": "sessionId",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/xml": {
                "schema": {
                  "format": "binary",
                  "type": "string"
                }
              }
            },
            "description": "XML download"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Download eLTAX municipal tax XML",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/eltax/generate-local-tax-xml": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Local tax XML generated"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Generate eLTAX local tax XML",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/eltax/generate-municipal-tax-xml": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Municipal tax XML generated"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Generate eLTAX municipal tax XML",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/etax-api/basic-info": {
      "get": {
        "description": "Retrieve basic taxpayer information from ETax system.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "address": {
                          "example": "東京都渋谷区...",
                          "type": "string"
                        },
                        "name": {
                          "example": "株式会社サンプル",
                          "type": "string"
                        },
                        "tax_office": {
                          "example": "渋谷税務署",
                          "type": "string"
                        },
                        "taxpayer_id": {
                          "example": "TP123456789",
                          "type": "string"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Basic information retrieved",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Basic information retrieved"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get ETax basic information",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/etax-api/capabilities": {
      "get": {
        "description": "Retrieve the capabilities and features available in the ETax API.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "api_version": {
                          "example": "2.0",
                          "type": "string"
                        },
                        "max_file_size": {
                          "example": 10485760,
                          "type": "integer"
                        },
                        "supported_operations": {
                          "example": [
                            "session_management",
                            "message_retrieval",
                            "filing_history"
                          ],
                          "items": {
                            "type": "string"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "ETax API capabilities retrieved",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "ETax API capabilities retrieved"
          }
        },
        "summary": "Get ETax API capabilities",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/etax-api/filings": {
      "get": {
        "description": "Retrieve tax filing history with filtering options.",
        "parameters": [
          {
            "description": "Tax year",
            "in": "query",
            "name": "year",
            "required": false,
            "schema": {
              "default": 2024,
              "type": "integer"
            }
          },
          {
            "description": "Tax type",
            "in": "query",
            "name": "tax_type",
            "required": false,
            "schema": {
              "default": "income",
              "type": "string"
            }
          },
          {
            "description": "Page number",
            "in": "query",
            "name": "page",
            "required": false,
            "schema": {
              "default": 1,
              "type": "integer"
            }
          },
          {
            "description": "Filings per page",
            "in": "query",
            "name": "limit",
            "required": false,
            "schema": {
              "default": 20,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "filings": {
                          "items": {
                            "properties": {
                              "filed_at": {
                                "example": "2024-01-15T10:30:00.000Z",
                                "format": "date-time",
                                "type": "string"
                              },
                              "filing_id": {
                                "example": "filing_123456",
                                "type": "string"
                              },
                              "status": {
                                "example": "accepted",
                                "type": "string"
                              },
                              "tax_type": {
                                "example": "income",
                                "type": "string"
                              },
                              "year": {
                                "example": 2024,
                                "type": "integer"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        },
                        "pagination": {
                          "properties": {
                            "limit": {
                              "example": 20,
                              "type": "integer"
                            },
                            "page": {
                              "example": 1,
                              "type": "integer"
                            },
                            "total": {
                              "example": 50,
                              "type": "integer"
                            }
                          },
                          "type": "object"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Filing history retrieved",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Filing history retrieved"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get filing history",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/etax-api/messages": {
      "get": {
        "description": "Retrieve messages from the ETax system with pagination and filtering.",
        "parameters": [
          {
            "description": "Page number",
            "in": "query",
            "name": "page",
            "required": false,
            "schema": {
              "default": 1,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "description": "Messages per page",
            "in": "query",
            "name": "limit",
            "required": false,
            "schema": {
              "default": 20,
              "maximum": 100,
              "type": "integer"
            }
          },
          {
            "description": "Message status filter",
            "in": "query",
            "name": "status",
            "required": false,
            "schema": {
              "default": "all",
              "enum": [
                "all",
                "unread",
                "read"
              ],
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "messages": {
                          "items": {
                            "properties": {
                              "message_id": {
                                "example": "msg_123456",
                                "type": "string"
                              },
                              "received_at": {
                                "example": "2024-01-15T10:30:00.000Z",
                                "format": "date-time",
                                "type": "string"
                              },
                              "sender": {
                                "example": "税務署",
                                "type": "string"
                              },
                              "status": {
                                "example": "unread",
                                "type": "string"
                              },
                              "subject": {
                                "example": "Tax filing notification",
                                "type": "string"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        },
                        "pagination": {
                          "properties": {
                            "limit": {
                              "example": 20,
                              "type": "integer"
                            },
                            "page": {
                              "example": 1,
                              "type": "integer"
                            },
                            "total": {
                              "example": 150,
                              "type": "integer"
                            }
                          },
                          "type": "object"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Messages retrieved successfully",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Messages retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get ETax messages",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/etax-api/messages/{message_id}": {
      "get": {
        "description": "Retrieve detailed information for a specific ETax message.",
        "parameters": [
          {
            "description": "Message ID",
            "example": "msg_123456",
            "in": "path",
            "name": "message_id",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "attachments": {
                          "items": {
                            "properties": {
                              "filename": {
                                "example": "notice.pdf",
                                "type": "string"
                              },
                              "size": {
                                "example": 1024000,
                                "type": "integer"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        },
                        "content": {
                          "example": "Your tax filing has been processed...",
                          "type": "string"
                        },
                        "message_id": {
                          "example": "msg_123456",
                          "type": "string"
                        },
                        "received_at": {
                          "example": "2024-01-15T10:30:00.000Z",
                          "format": "date-time",
                          "type": "string"
                        },
                        "sender": {
                          "example": "税務署",
                          "type": "string"
                        },
                        "status": {
                          "example": "read",
                          "type": "string"
                        },
                        "subject": {
                          "example": "Tax filing notification",
                          "type": "string"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Message details retrieved",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Message details retrieved"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get ETax message details",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/etax-api/receipts/import": {
      "post": {
        "description": "Assisted fetch of 受信通知 from the e-Tax message box into the filing workspace (auditor view + audit pack). Requires a stored e-Tax session (POST /compliance/etax-api/session). Demo mode returns mock data when ETAX_API_KEY is not configured.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "fiscal_year": {
                    "example": 2025,
                    "type": "integer"
                  },
                  "limit": {
                    "description": "Max receipts to import this call",
                    "type": "integer"
                  }
                },
                "type": "object"
              }
            }
          },
          "required": false
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "demoMode": {
                          "type": "boolean"
                        },
                        "imported": {
                          "type": "integer"
                        },
                        "skipped": {
                          "type": "integer"
                        }
                      },
                      "type": "object"
                    },
                    "demoMode": {
                      "type": "boolean"
                    },
                    "message": {
                      "type": "string"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Import summary"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Import e-Tax 受信通知 into filing workspace",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/etax-api/session": {
      "delete": {
        "description": "Clear the stored ETax session and invalidate tokens.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "example": "ETax session has been cleared",
                      "type": "string"
                    },
                    "message": {
                      "example": "Session cleared successfully",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Session cleared successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Clear ETax session",
        "tags": [
          "Compliance"
        ]
      },
      "get": {
        "description": "Retrieve the current ETax session status and information.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ETaxSessionResponse"
                }
              }
            },
            "description": "Session status retrieved"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get ETax session status",
        "tags": [
          "Compliance"
        ]
      },
      "post": {
        "description": "Store ETax session token for authenticated operations.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/StoreSessionRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ETaxSessionResponse"
                }
              }
            },
            "description": "Session stored successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Store ETax session",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/etax-api/status": {
      "get": {
        "description": "Check the status and availability of the ETax API service.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HealthStatusResponse"
                }
              }
            },
            "description": "ETax API status retrieved"
          }
        },
        "summary": "Check ETax API status",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/etax-api/tax/{year}/{tax_type}": {
      "get": {
        "description": "Retrieve specific tax information by year and type.",
        "parameters": [
          {
            "description": "Tax year",
            "example": 2024,
            "in": "path",
            "name": "year",
            "required": true,
            "schema": {
              "type": "integer"
            }
          },
          {
            "description": "Tax type",
            "example": "income",
            "in": "path",
            "name": "tax_type",
            "required": true,
            "schema": {
              "enum": [
                "income",
                "corporate",
                "consumption"
              ],
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "deductions": {
                          "example": 1000000,
                          "type": "number"
                        },
                        "status": {
                          "example": "filed",
                          "type": "string"
                        },
                        "tax_type": {
                          "example": "income",
                          "type": "string"
                        },
                        "total_income": {
                          "example": 5000000,
                          "type": "number"
                        },
                        "total_tax": {
                          "example": 500000,
                          "type": "number"
                        },
                        "year": {
                          "example": 2024,
                          "type": "integer"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Tax information retrieved",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Tax information retrieved"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get specific tax information",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/etax/compare": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Compare result"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Diff imported filing baselines vs live ledger (FilingCompareService)",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/etax/download-xtx/{sessionId}": {
      "get": {
        "parameters": [
          {
            "in": "path",
            "name": "sessionId",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/octet-stream": {
                "schema": {
                  "format": "binary",
                  "type": "string"
                }
              }
            },
            "description": "XTX file download (best-effort download stamp; download still succeeds if stamp fails)"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Download generated XTX; stamps tax_return_sessions.last_downloaded_at",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/etax/download/{type}/{year}": {
      "get": {
        "description": "Download generated tax documents by type and year.",
        "parameters": [
          {
            "description": "Document type",
            "example": "withholding-slip",
            "in": "path",
            "name": "type",
            "required": true,
            "schema": {
              "enum": [
                "withholding-slip",
                "hotei-chosho-total"
              ],
              "type": "string"
            }
          },
          {
            "description": "Tax year",
            "example": 2024,
            "in": "path",
            "name": "year",
            "required": true,
            "schema": {
              "maximum": 2030,
              "minimum": 2020,
              "type": "integer"
            }
          },
          {
            "description": "Payee name filter (withholding-slip needs this or employee_id)",
            "example": "田中太郎",
            "in": "query",
            "name": "payee_name",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "employees.id of the payee (BL-219); selects rows by employee rather than by name. Takes precedence over payee_name.",
            "in": "query",
            "name": "employee_id",
            "required": false,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/pdf": {
                "schema": {
                  "format": "binary",
                  "type": "string"
                }
              },
              "application/xml": {
                "schema": {
                  "example": "<?xml version=\"1.0\"...",
                  "type": "string"
                }
              }
            },
            "description": "Document downloaded successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Download tax document",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/etax/files/{sessionId}": {
      "delete": {
        "parameters": [
          {
            "in": "path",
            "name": "sessionId",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Session deleted"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Delete a generated filing session",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/etax/files/{sessionId}/submission": {
      "patch": {
        "parameters": [
          {
            "in": "path",
            "name": "sessionId",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Submission updated"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Record submission / receipt metadata on a filing session",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/etax/files/{year}": {
      "get": {
        "description": "Returns tax_return_sessions for the year, including lastDownloadedAt when set on download.",
        "parameters": [
          {
            "in": "path",
            "name": "year",
            "required": true,
            "schema": {
              "example": 2025,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Filing session list"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List generated filing sessions for a year",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/etax/generate-all": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Batch generate result"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Generate all configured e-Tax / eLTAX packages for a year",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/etax/generate-xtx": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "XTX generated; returns session id + summary"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Generate e-Tax XTX package for a tax type / year",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/etax/hotei-chosho-total": {
      "post": {
        "description": "Generate XML document for hotei chosho total submission. Use /generate endpoint for selective inclusion.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/HoteiChoshoTotalRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ETaxXMLResponse"
                }
              }
            },
            "description": "Hotei chosho total XML generated"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Generate hotei chosho total XML (legacy)",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/etax/hotei-chosho-total/generate": {
      "post": {
        "description": "\nGenerate 法定調書合計表 XML with selective record inclusion.\n\n## Data Sources (v4.59)\nThis endpoint now correctly processes BOTH data sources:\n\n1. **Salary Slip Documents** (`include_salary_slip_ids`)\n   - Source: `documents` table with `document_type='salary_slip'`\n   - Get IDs from preview: `categories.salary.employees[].records[].documentId`\n\n2. **Withholding Tax Records** (`include_withholding_ids`)\n   - Source: `withholding_taxes` table\n   - Get IDs from preview: `categories.freelance/royalty/other[].id`\n\n## Behavior\n\n| Request | Result |\n|---------|--------|\n| `{ year: 2025 }` | Include ALL eligible records |\n| `{ year: 2025, include_salary_slip_ids: [...] }` | Include only specified salary slips |\n| `{ year: 2025, include_withholding_ids: [...] }` | Include only specified withholding records |\n| `{ year: 2025, include_salary_slip_ids: [...], include_withholding_ids: [...] }` | Include both specified sets |\n\n## Limits\n- Maximum 500 IDs per array\n- IDs must be valid UUIDs\n- IDs must belong to the authenticated user\n      ",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/HoteiChoshoGenerateRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ETaxXMLResponse"
                }
              }
            },
            "description": "Hotei chosho total XML generated"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Generate 法定調書合計表 XML with selective inclusion (v4.59 Fixed)",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/etax/hotei-chosho-total/preview": {
      "get": {
        "description": "\nPreview aggregated data for 法定調書合計表 (Total Table of Legal Reports) generation.\n\n## Returns\n- Salary records grouped by employee (from salary_slip documents and withholding_taxes)\n- Contractor payments (freelance fees, royalties, etc.)\n- Subtotals by category\n- **taxableSummary**: Breakdown of taxable vs non-taxable payments\n- Warnings for drafts, missing addresses, etc.\n\n## Payment Classification (v4.36)\nEach salary record includes:\n- **paymentCategory**: Classification of payment type (salary, director_salary, bonus, expense_reimbursement, travel_settlement, etc.)\n- **isTaxable**: Whether the payment is taxable income\n- **bankTransactionId**: Link to bank transaction if payment is confirmed\n\n### Taxable Categories\n- `salary` - 給与 (regular employee salary)\n- `director_salary` - 役員報酬 (director compensation)\n- `bonus` - 賞与 (bonus payments)\n- `freelance_fee` - 報酬 (contractor fees; also covers `professional_fee` 2号 報酬 withholding rows)\n\n### Non-Taxable Categories (excluded from 法定調書)\n- `expense_reimbursement` - 経費精算\n- `travel_settlement` - 出張精算\n- `advance_settlement` - 立替精算\n\nUse this endpoint to allow users to review and select which records to include before generating the XML.\n      ",
        "parameters": [
          {
            "description": "Tax year",
            "example": 2025,
            "in": "query",
            "name": "year",
            "required": true,
            "schema": {
              "maximum": 2030,
              "minimum": 2020,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HoteiChoshoPreviewResponse"
                }
              }
            },
            "description": "Preview data retrieved"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Preview 法定調書合計表 data",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/etax/import-preview": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Import preview"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Preview import of an external filing package",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/etax/import-xtx/apply": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "XTX import applied"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Apply a previously previewed XTX import",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/etax/import-xtx/preview": {
      "post": {
        "requestBody": {
          "content": {
            "multipart/form-data": {
              "schema": {
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "XTX import preview"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Preview XTX import (parse without apply)",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/etax/pdf-crosscheck": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "PDF crosscheck result"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Cross-check generated filing PDF against ledger / session summary",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/etax/withholding-slip": {
      "post": {
        "description": "Generate XML document for withholding slip submission.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/WithholdingSlipRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ETaxXMLResponse"
                }
              }
            },
            "description": "Withholding slip XML generated"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Generate withholding slip XML",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/health": {
      "get": {
        "description": "Check the health status of the compliance service and its dependencies.\n      \n## Health Monitoring\n- **Service Status**: Overall compliance service health\n- **Dependency Checks**: External API connectivity and status\n- **Performance Metrics**: Response times and throughput\n- **System Resources**: Memory and CPU usage statistics\n\n## Integration Status\n- **NTA APIs**: Invoice and corporate number API connectivity\n- **MLIT APIs**: Real estate data API status\n- **ETax Systems**: Tax filing system connectivity\n- **Database**: Data storage and retrieval performance\n\n## Use Cases\n- **System Monitoring**: Automated health checks and alerting\n- **Load Balancing**: Health-based traffic routing decisions\n- **Maintenance**: Service status during updates and maintenance\n- **Troubleshooting**: Quick diagnosis of service issues",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "healthy-service": {
                    "summary": "Healthy compliance service",
                    "value": {
                      "data": {
                        "status": "healthy",
                        "timestamp": "2024-01-15T10:30:00.000Z",
                        "uptime": 3600,
                        "version": "1.0.0"
                      },
                      "message": "Service is healthy",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/HealthStatusResponse"
                }
              }
            },
            "description": "Service is healthy"
          },
          "503": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Service unavailable"
          }
        },
        "summary": "Check overall compliance service health",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/invoice/cache/clear": {
      "post": {
        "description": "Clear the cache for invoice verification data.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "example": "Invoice cache has been cleared",
                      "type": "string"
                    },
                    "message": {
                      "example": "Cache cleared successfully",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Cache cleared successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Clear invoice verification cache",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/invoice/status": {
      "get": {
        "description": "Check the status and availability of the NTA invoice verification service.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HealthStatusResponse"
                }
              }
            },
            "description": "Invoice service status retrieved"
          }
        },
        "summary": "Check invoice verification service status",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/invoice/verify": {
      "post": {
        "description": "Verify the validity of a Japanese invoice registration number with the National Tax Agency.\n      \n## Invoice Verification Process\n- **Registration Check**: Validates format and existence of registration number\n- **Company Information**: Retrieves associated company details\n- **Status Verification**: Confirms current registration status\n- **Historical Data**: Optional historical verification information\n\n## Compliance Features\n- **NTA Integration**: Direct integration with National Tax Agency systems\n- **Real-time Verification**: Live verification against official records\n- **Audit Trail**: Complete audit logging for compliance purposes\n- **Rate Limiting**: Respects NTA API rate limits and quotas\n\n## Use Cases\n- **Invoice Processing**: Verify supplier registration before payment\n- **Compliance Checks**: Ensure all business partners are properly registered\n- **Audit Preparation**: Gather verification records for tax audits\n- **Risk Management**: Identify potentially fraudulent registration numbers",
        "parameters": [
          {
            "description": "Invoice registration number (T + 13 digits)",
            "example": "T1234567890123",
            "in": "query",
            "name": "registration_number",
            "required": true,
            "schema": {
              "pattern": "^T\\d{13}$",
              "type": "string"
            }
          },
          {
            "description": "Include historical verification data",
            "in": "query",
            "name": "include_history",
            "required": false,
            "schema": {
              "default": false,
              "type": "boolean"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "valid-registration": {
                    "summary": "Valid registration number",
                    "value": {
                      "data": {
                        "company_name": "株式会社サンプル",
                        "is_valid": true,
                        "registration_date": "2023-10-01",
                        "registration_number": "T1234567890123",
                        "status": "active",
                        "verification_date": "2024-01-15T10:30:00.000Z"
                      },
                      "message": "Invoice verification completed",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/InvoiceVerificationResponse"
                }
              }
            },
            "description": "Invoice verification completed successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Invalid registration number format"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Rate limit exceeded"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Verify invoice registration number",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/invoice/verify-bulk": {
      "post": {
        "description": "Verify multiple invoice registration numbers in a single request for efficient batch processing.\n      \n## Bulk Verification Benefits\n- **Batch Processing**: Verify up to 100 registration numbers at once\n- **Performance Optimization**: Reduced API calls and improved throughput\n- **Cost Efficiency**: Lower API usage costs for bulk operations\n- **Consistent Results**: All verifications processed with same timestamp\n\n## Processing Features\n- **Parallel Processing**: Concurrent verification for faster results\n- **Error Isolation**: Individual failures don't affect other verifications\n- **Progress Tracking**: Monitor bulk operation progress and completion\n- **Result Aggregation**: Consolidated results with success/failure counts\n\n## Use Cases\n- **Supplier Onboarding**: Verify all supplier registration numbers at once\n- **Periodic Audits**: Batch verification of existing business partners\n- **Data Migration**: Verify registration numbers during system migrations\n- **Compliance Reporting**: Generate bulk verification reports for audits",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "bulk-verification": {
                  "summary": "Bulk invoice verification request",
                  "value": {
                    "registration_numbers": [
                      "T1234567890123",
                      "T9876543210987",
                      "T5555555555555"
                    ]
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/BulkInvoiceVerificationRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "results": {
                          "items": {
                            "$ref": "#/components/schemas/InvoiceVerificationDetail"
                          },
                          "type": "array"
                        },
                        "summary": {
                          "properties": {
                            "invalid": {
                              "example": 1,
                              "type": "integer"
                            },
                            "total": {
                              "example": 3,
                              "type": "integer"
                            },
                            "valid": {
                              "example": 2,
                              "type": "integer"
                            }
                          },
                          "type": "object"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Bulk verification completed",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Bulk verification completed"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Rate limit exceeded"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Bulk verify multiple invoice registration numbers",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/invoice/verify-on-date": {
      "get": {
        "description": "Verify the status of an invoice registration number on a specific date.",
        "parameters": [
          {
            "description": "Invoice registration number",
            "example": "T1234567890123",
            "in": "query",
            "name": "registration_number",
            "required": true,
            "schema": {
              "pattern": "^T\\d{13}$",
              "type": "string"
            }
          },
          {
            "description": "Date to check (YYYY-MM-DD)",
            "example": "2024-01-15",
            "in": "query",
            "name": "date",
            "required": true,
            "schema": {
              "format": "date",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/InvoiceVerificationResponse"
                }
              }
            },
            "description": "Invoice verification on date completed"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Verify invoice registration on specific date",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/real-estate/appraisals": {
      "get": {
        "description": "Retrieve real estate appraisal data by year, prefecture, and division.",
        "parameters": [
          {
            "description": "Appraisal year",
            "example": 2024,
            "in": "query",
            "name": "year",
            "required": true,
            "schema": {
              "minimum": 2005,
              "type": "integer"
            }
          },
          {
            "description": "Prefecture name",
            "example": "東京都",
            "in": "query",
            "name": "prefecture",
            "required": true,
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "Division code",
            "example": "13",
            "in": "query",
            "name": "division",
            "required": true,
            "schema": {
              "enum": [
                "00",
                "03",
                "05",
                "07",
                "09",
                "10",
                "13",
                "20"
              ],
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "appraisals": {
                          "items": {
                            "properties": {
                              "appraisal_date": {
                                "example": "2024-01-01",
                                "format": "date",
                                "type": "string"
                              },
                              "appraisal_id": {
                                "example": "app_123456",
                                "type": "string"
                              },
                              "appraised_value": {
                                "example": 1000000000,
                                "type": "number"
                              },
                              "building_area": {
                                "example": 2000,
                                "type": "number"
                              },
                              "land_area": {
                                "example": 500.5,
                                "type": "number"
                              },
                              "location": {
                                "example": "東京都千代田区丸の内1-1-1",
                                "type": "string"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Appraisals retrieved successfully",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Appraisals retrieved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get real estate appraisals",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/real-estate/cache/clear": {
      "post": {
        "description": "Clear the cache for real estate GIS data.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "example": "Real estate GIS cache has been cleared",
                      "type": "string"
                    },
                    "message": {
                      "example": "Cache cleared successfully",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Cache cleared successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Clear real estate GIS cache",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/real-estate/gis/available": {
      "get": {
        "description": "Retrieve the list of available GIS APIs and their capabilities.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "apis": {
                          "items": {
                            "properties": {
                              "api_code": {
                                "example": "hazard_map",
                                "type": "string"
                              },
                              "description": {
                                "example": "Provides hazard map data for disaster risk assessment",
                                "type": "string"
                              },
                              "name": {
                                "example": "Hazard Map API",
                                "type": "string"
                              },
                              "status": {
                                "example": "active",
                                "type": "string"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Available GIS APIs retrieved",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Available GIS APIs retrieved"
          }
        },
        "summary": "Get available GIS APIs",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/real-estate/gis/{api_code}": {
      "get": {
        "description": "Retrieve GIS data using a specific API code and coordinates.",
        "parameters": [
          {
            "description": "GIS API code",
            "example": "hazard_map",
            "in": "path",
            "name": "api_code",
            "required": true,
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "Zoom level",
            "example": 15,
            "in": "query",
            "name": "z",
            "required": true,
            "schema": {
              "type": "integer"
            }
          },
          {
            "description": "X coordinate",
            "example": 29100,
            "in": "query",
            "name": "x",
            "required": true,
            "schema": {
              "type": "integer"
            }
          },
          {
            "description": "Y coordinate",
            "example": 12900,
            "in": "query",
            "name": "y",
            "required": true,
            "schema": {
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "api_code": {
                          "example": "hazard_map",
                          "type": "string"
                        },
                        "coordinates": {
                          "properties": {
                            "x": {
                              "example": 29100,
                              "type": "integer"
                            },
                            "y": {
                              "example": 12900,
                              "type": "integer"
                            },
                            "z": {
                              "example": 15,
                              "type": "integer"
                            }
                          },
                          "type": "object"
                        },
                        "data": {
                          "description": "GIS-specific data structure varies by API",
                          "type": "object"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "GIS data retrieved successfully",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "GIS data retrieved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get GIS data by API code",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/real-estate/land-prices": {
      "get": {
        "description": "Retrieve land price data by coordinates and year.",
        "parameters": [
          {
            "description": "Price data year",
            "example": 2024,
            "in": "query",
            "name": "year",
            "required": true,
            "schema": {
              "minimum": 2005,
              "type": "integer"
            }
          },
          {
            "description": "Zoom level",
            "example": 15,
            "in": "query",
            "name": "z",
            "required": true,
            "schema": {
              "type": "integer"
            }
          },
          {
            "description": "X coordinate",
            "example": 29100,
            "in": "query",
            "name": "x",
            "required": true,
            "schema": {
              "type": "integer"
            }
          },
          {
            "description": "Y coordinate",
            "example": 12900,
            "in": "query",
            "name": "y",
            "required": true,
            "schema": {
              "type": "integer"
            }
          },
          {
            "description": "Price classification",
            "in": "query",
            "name": "price_classification",
            "required": false,
            "schema": {
              "enum": [
                "01",
                "02"
              ],
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "land_prices": {
                          "items": {
                            "properties": {
                              "coordinates": {
                                "properties": {
                                  "lat": {
                                    "example": 35.6812,
                                    "type": "number"
                                  },
                                  "lng": {
                                    "example": 139.7671,
                                    "type": "number"
                                  }
                                },
                                "type": "object"
                              },
                              "location": {
                                "example": "東京都千代田区丸の内",
                                "type": "string"
                              },
                              "price_per_sqm": {
                                "example": 5000000,
                                "type": "number"
                              },
                              "survey_date": {
                                "example": "2024-01-01",
                                "format": "date",
                                "type": "string"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Land prices retrieved successfully",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Land prices retrieved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get land price data",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/real-estate/municipalities": {
      "get": {
        "description": "Retrieve municipalities within a specific prefecture.",
        "parameters": [
          {
            "description": "Prefecture name",
            "example": "東京都",
            "in": "query",
            "name": "prefecture",
            "required": true,
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "Response language",
            "in": "query",
            "name": "language",
            "required": false,
            "schema": {
              "default": "ja",
              "enum": [
                "ja",
                "en"
              ],
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "municipalities": {
                          "items": {
                            "properties": {
                              "code": {
                                "example": "13101",
                                "type": "string"
                              },
                              "name": {
                                "example": "千代田区",
                                "type": "string"
                              },
                              "name_en": {
                                "example": "Chiyoda City",
                                "type": "string"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        },
                        "prefecture": {
                          "example": "東京都",
                          "type": "string"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Municipalities retrieved",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Municipalities retrieved"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get municipalities by prefecture",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/real-estate/prefectures": {
      "get": {
        "description": "Retrieve the list of all Japanese prefectures for real estate data filtering.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "prefectures": {
                          "items": {
                            "properties": {
                              "code": {
                                "example": "13",
                                "type": "string"
                              },
                              "name": {
                                "example": "東京都",
                                "type": "string"
                              },
                              "name_en": {
                                "example": "Tokyo",
                                "type": "string"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Prefectures list retrieved",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Prefectures list retrieved"
          }
        },
        "summary": "Get list of prefectures",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/real-estate/status": {
      "get": {
        "description": "Check the status and availability of the real estate data service.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HealthStatusResponse"
                }
              }
            },
            "description": "Real estate service status retrieved"
          }
        },
        "summary": "Check real estate service status",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/real-estate/transaction-points": {
      "get": {
        "description": "Retrieve real estate transaction points within specified coordinates and date range.",
        "parameters": [
          {
            "description": "Zoom level",
            "example": 15,
            "in": "query",
            "name": "z",
            "required": true,
            "schema": {
              "type": "integer"
            }
          },
          {
            "description": "X coordinate",
            "example": 29100,
            "in": "query",
            "name": "x",
            "required": true,
            "schema": {
              "type": "integer"
            }
          },
          {
            "description": "Y coordinate",
            "example": 12900,
            "in": "query",
            "name": "y",
            "required": true,
            "schema": {
              "type": "integer"
            }
          },
          {
            "description": "Start date",
            "example": "2024-01-01",
            "in": "query",
            "name": "from",
            "required": true,
            "schema": {
              "format": "date",
              "type": "string"
            }
          },
          {
            "description": "End date",
            "example": "2024-12-31",
            "in": "query",
            "name": "to",
            "required": true,
            "schema": {
              "format": "date",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "transaction_points": {
                          "items": {
                            "properties": {
                              "avg_price": {
                                "example": 80000000,
                                "type": "number"
                              },
                              "coordinates": {
                                "properties": {
                                  "lat": {
                                    "example": 35.6812,
                                    "type": "number"
                                  },
                                  "lng": {
                                    "example": 139.7671,
                                    "type": "number"
                                  }
                                },
                                "type": "object"
                              },
                              "period": {
                                "properties": {
                                  "from": {
                                    "example": "2024-01-01",
                                    "format": "date",
                                    "type": "string"
                                  },
                                  "to": {
                                    "example": "2024-12-31",
                                    "format": "date",
                                    "type": "string"
                                  }
                                },
                                "type": "object"
                              },
                              "point_id": {
                                "example": "point_123456",
                                "type": "string"
                              },
                              "transaction_count": {
                                "example": 15,
                                "type": "integer"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Transaction points retrieved successfully",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Transaction points retrieved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get transaction points data",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/compliance/real-estate/transactions": {
      "get": {
        "description": "Retrieve real estate transaction data from the Ministry of Land, Infrastructure, Transport and Tourism (MLIT).\n      \n## Transaction Data Features\n- **Official Records**: Government-verified transaction data\n- **Market Analysis**: Comprehensive market trend information\n- **Location-based**: Filter by prefecture, city, and station proximity\n- **Time Series**: Historical transaction data by year and quarter\n\n## Data Sources\n- **MLIT Integration**: Direct access to official real estate databases\n- **Verified Transactions**: Only completed and verified transactions\n- **Market Standards**: Industry-standard data formats and classifications\n- **Regular Updates**: Data updated quarterly with latest transactions\n\n## Business Applications\n- **Property Valuation**: Market-based property value assessments\n- **Investment Analysis**: Real estate investment decision support\n- **Market Research**: Comprehensive market trend analysis\n- **Compliance Reporting**: Official data for regulatory reporting",
        "parameters": [
          {
            "description": "Transaction year",
            "example": 2024,
            "in": "query",
            "name": "year",
            "required": true,
            "schema": {
              "minimum": 2005,
              "type": "integer"
            }
          },
          {
            "description": "Quarter of the year",
            "in": "query",
            "name": "quarter",
            "required": false,
            "schema": {
              "default": 1,
              "enum": [
                1,
                2,
                3,
                4
              ],
              "type": "integer"
            }
          },
          {
            "description": "Area code or name",
            "example": "13101",
            "in": "query",
            "name": "area",
            "required": true,
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "City name",
            "example": "千代田区",
            "in": "query",
            "name": "city",
            "required": true,
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "Nearest station name",
            "example": "東京駅",
            "in": "query",
            "name": "station",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RealEstateTransactionResponse"
                }
              }
            },
            "description": "Real estate transactions retrieved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Rate limit exceeded"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get real estate transaction data",
        "tags": [
          "Compliance"
        ]
      }
    },
    "/consumption-tax/apportionment": {
      "get": {
        "description": "課税売上割合 (付表2-3 ①〜⑧) and the 控除対象仕入税額 under 全額控除 / 個別対応方式 / 一括比例配分方式 for one 課税期間, the recorded election, the 消法30条5項 lock, the 用途区分 list ordered by the national tax each line moves, and 調整対象固定資産 notices (消法33条). Read-only.\n\nA 課税期間 below 95% (or over ¥5億 annualized) cannot generate XTX until a method is elected and, for 個別対応方式, every creditable line has a 用途区分 (消基通11-2-18). See docs/adr/0007-input-tax-apportionment.md.",
        "parameters": [
          {
            "in": "query",
            "name": "fiscalYear",
            "required": true,
            "schema": {
              "example": 2026,
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "periodStart",
            "required": true,
            "schema": {
              "example": 20260516,
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "periodEnd",
            "required": true,
            "schema": {
              "example": 20260815,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ApportionmentOverviewResponse"
                }
              }
            },
            "description": "Apportionment overview"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "仕入税額の按分 review for one 課税期間 (個別対応方式 / 一括比例配分方式)",
        "tags": [
          "Consumption Tax"
        ]
      }
    },
    "/consumption-tax/apportionment/credit-override": {
      "put": {
        "description": "The line then credits nothing (付表2-3 ⑨ and ⑪ exclude it at any ratio) and is listed in `overriddenLines` instead of the 用途区分 list.\n\n- `residential_rental_building` — 居住用賃貸建物 (消法30条10項). Accepted only on a 建物 (附属設備を含む) asset line of 税抜 ¥1,000万 or more (400, reason `not_high_value_building`).\n- `invoice_not_held` — a registered supplier's 適格請求書 is not held (消法30条7項). Any purchase line with a positive amount (400, `not_a_purchase`).\n- `other_period` — the 課税仕入れ belongs to another 課税期間 (消法30条1項); it credits nothing here and the other period claims it. Any purchase line with a positive amount (400, `not_a_purchase`) whose own purchase date lies outside this 課税期間 (400, `purchase_date_in_period`). The purchase date is the credit engine's: an explicit 課税仕入れの日, else the line date, else the 仕訳 date for a line date more than 366 days away.\n- `reason: null` clears it (409, `no_override`, when none is set).\n\nA note is required to set or clear. The line must be a 課税仕入れ of the period (404). Each write stamps field provenance, and the line's version trigger keeps the before/after.\n\nThe override moves the line's credit, so a filed or closed 課税期間 refuses it (**423** `PERIOD_LOCKED`, BE ADR-0011) — including a quarter whose return is filed while its period row is still open — unless a 修正申告 for that fiscal year is open (`X-Filing-Amendment-Year` + `x-filing-change-reason`). The periods checked are those of the 仕訳 date, the line date and its 課税仕入れの日; setting or clearing `other_period` checks the 仕訳 (booking) date only, so a filed purchase quarter does not refuse it.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "fiscalYear": {
                    "example": 2026,
                    "type": "integer"
                  },
                  "lineId": {
                    "format": "uuid",
                    "type": "string"
                  },
                  "note": {
                    "maxLength": 200,
                    "minLength": 1,
                    "type": "string"
                  },
                  "periodEnd": {
                    "example": 20260815,
                    "type": "integer"
                  },
                  "periodStart": {
                    "example": 20260516,
                    "type": "integer"
                  },
                  "reason": {
                    "enum": [
                      "residential_rental_building",
                      "invoice_not_held",
                      "other_period",
                      null
                    ],
                    "nullable": true,
                    "type": "string"
                  }
                },
                "required": [
                  "fiscalYear",
                  "periodStart",
                  "periodEnd",
                  "lineId",
                  "reason",
                  "note"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ApportionmentOverviewResponse"
                }
              }
            },
            "description": "Override set or cleared; returns the refreshed overview"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "$ref": "#/components/responses/Conflict"
          },
          "423": {
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetails"
                }
              }
            },
            "description": "The 課税期間 is filed or closed (PERIOD_LOCKED) and no 修正申告 for its year is open"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Set or clear the owner’s zero-credit override on one purchase line",
        "tags": [
          "Consumption Tax"
        ]
      }
    },
    "/consumption-tax/apportionment/election": {
      "put": {
        "description": "Stores the method on consumption_tax_periods with who/when and field provenance; the row is audited (audit_logs).\n\n- `proportional` requires `acknowledgeLock: true`: it binds every 課税期間 starting within two years (消法30条5項, 国税通則法10条).\n- `individual` is refused (422) while an earlier FILED 一括比例配分方式 still binds.\n- A period at ≥95% (and ≤¥5億) needs no method and is refused (400, reason `apportionment_not_required`): an election there would start a lock the law never imposes.\n- A filed period cannot change method (409, `period_filed`): SBC treats a recorded method as final (a return filed under 一括比例 cannot be switched to 個別対応 by 更正の請求 — 国税不服審判所 平成21年9月18日裁決). A filed return that recorded no method takes one once; a second election is refused (409, `method_already_recorded`).",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "acknowledgeLock": {
                    "default": false,
                    "type": "boolean"
                  },
                  "fiscalYear": {
                    "example": 2026,
                    "type": "integer"
                  },
                  "method": {
                    "enum": [
                      "individual",
                      "proportional"
                    ],
                    "type": "string"
                  },
                  "periodEnd": {
                    "example": 20260815,
                    "type": "integer"
                  },
                  "periodStart": {
                    "example": 20260516,
                    "type": "integer"
                  }
                },
                "required": [
                  "fiscalYear",
                  "periodStart",
                  "periodEnd",
                  "method"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ApportionmentOverviewResponse"
                }
              }
            },
            "description": "Election recorded; returns the refreshed overview"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "$ref": "#/components/responses/Conflict"
          },
          "422": {
            "$ref": "#/components/responses/BadRequest"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Record 個別対応方式 or 一括比例配分方式 for an open 課税期間",
        "tags": [
          "Consumption Tax"
        ]
      }
    },
    "/consumption-tax/apportionment/lines": {
      "patch": {
        "description": "Up to 500 lines per call. Every line must belong to the caller and sit in the period (404 otherwise — the whole batch is rejected). `useCategory: null` returns a line to automatic classification. Each write stamps field provenance (src/utils/provenance.ts) and the line's version trigger keeps the before/after.\n\nA 用途区分 moves the period's ㉑, so a filed or closed 課税期間 refuses it (**423** `PERIOD_LOCKED`, BE ADR-0012) — including a quarter whose return is filed while its period row is still open — unless a 修正申告 for that fiscal year is open (`X-Filing-Amendment-Year` + `x-filing-change-reason`). Only the lines' 仕訳 (booking) dates are checked, so a line bought in a filed quarter but booked in this open one stays classifiable.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "fiscalYear": {
                    "example": 2026,
                    "type": "integer"
                  },
                  "periodEnd": {
                    "example": 20260815,
                    "type": "integer"
                  },
                  "periodStart": {
                    "example": 20260516,
                    "type": "integer"
                  },
                  "updates": {
                    "items": {
                      "properties": {
                        "lineId": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "useCategory": {
                          "enum": [
                            "taxable_only",
                            "exempt_only",
                            "common",
                            null
                          ],
                          "nullable": true,
                          "type": "string"
                        }
                      },
                      "required": [
                        "lineId",
                        "useCategory"
                      ],
                      "type": "object"
                    },
                    "maxItems": 500,
                    "minItems": 1,
                    "type": "array"
                  }
                },
                "required": [
                  "fiscalYear",
                  "periodStart",
                  "periodEnd",
                  "updates"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/UseCategoryClassificationResponse"
                }
              }
            },
            "description": "Lines classified; returns the refreshed summary"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "$ref": "#/components/responses/Conflict"
          },
          "423": {
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetails"
                }
              }
            },
            "description": "The 課税期間 is filed or closed (PERIOD_LOCKED) and no 修正申告 for its year is open"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Set or clear 用途区分 on purchase lines of an open 課税期間",
        "tags": [
          "Consumption Tax"
        ]
      }
    },
    "/consumption-tax/calculate": {
      "get": {
        "description": "Calculate consumption tax return using specified method and parameters.\n\n## Consumption Tax Calculation (消費税申告額計算)\nComprehensive tax calculation with:\n- **Multiple Methods**: Support for general, simplified, and 20% special rule calculations\n- **Multi-Tax Rate**: Handle both standard 10% and reduced 8% tax rates\n- **Business Classification**: Apply appropriate business type for simplified taxation\n- **Data Integration**: Integrate with journal entries, expenses, and sales invoices\n- **Optimization**: Automatic recommendation for most advantageous method\n- **Compliance**: Full compliance with Japanese consumption tax law\n\n## Calculation Methods\n- **General Taxation (一般課税)**: Standard method using actual input and output tax amounts\n  - Most accurate method reflecting actual business transactions\n  - Requires detailed record keeping and invoice preservation\n  - Advantageous when actual purchase tax is high\n- **Simplified Taxation (簡易課税)**: Uses deemed purchase rates by business type\n  - Simplified bookkeeping requirements\n  - Fixed deemed purchase rates: 90% (wholesale), 80% (retail), 70% (manufacturing), 60% (other), 50% (service), 40% (real estate)\n  - Eligible when base period sales ≤ ¥50,000,000\n- **20% Special Rule (2割特例)**: Special transitional measure for new registrants\n  - Pay 20% of output tax as final tax due\n  - Available until September 30, 2026\n  - For businesses newly registered due to Invoice System\n\n## Tax Rates\n- **Standard 10% (標準税率)**: Regular consumption tax rate for most goods and services\n- **Reduced 8% (軽減税率)**: Reduced rate for food, beverages, and newspapers\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Fiscal year for calculation",
            "in": "query",
            "name": "fiscal_year",
            "required": true,
            "schema": {
              "example": 2024,
              "type": "integer"
            }
          },
          {
            "description": "Period start date in YYYYMMDD format",
            "in": "query",
            "name": "period_start",
            "required": true,
            "schema": {
              "example": 20240101,
              "type": "integer"
            }
          },
          {
            "description": "Period end date in YYYYMMDD format",
            "in": "query",
            "name": "period_end",
            "required": true,
            "schema": {
              "example": 20241231,
              "type": "integer"
            }
          },
          {
            "description": "Specific calculation method (optional, will use optimal if not specified)",
            "in": "query",
            "name": "calculation_method",
            "required": false,
            "schema": {
              "$ref": "#/components/schemas/TaxCalculationMethod"
            }
          },
          {
            "description": "Business type for simplified taxation (required if using simplified method)",
            "in": "query",
            "name": "business_type",
            "required": false,
            "schema": {
              "$ref": "#/components/schemas/BusinessType"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ConsumptionTaxCalculationResponse"
                }
              }
            },
            "description": "Consumption tax calculation completed successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Calculate consumption tax return (消費税申告額計算)",
        "tags": [
          "Consumption Tax"
        ]
      }
    },
    "/consumption-tax/compare": {
      "get": {
        "description": "Compare all available calculation methods and provide optimization recommendations.\n\n## Method Comparison (計算方法比較)\nComprehensive method analysis with:\n- **All Methods**: Calculate tax due using general, simplified, and 20% special rule\n- **Optimization**: Identify the most advantageous method for tax minimization\n- **Savings Analysis**: Calculate potential tax savings with optimal method\n- **Detailed Explanations**: Provide detailed explanations for each method\n- **Recommendations**: AI-powered recommendations with reasoning\n- **Decision Support**: Help businesses choose the best calculation method\n\n## Comparison Features\n- **Side-by-Side Analysis**: Compare tax due amounts for all methods\n- **Method Descriptions**: Detailed descriptions of each calculation method\n- **Deemed Rates**: Show deemed purchase rates for simplified taxation\n- **Savings Calculation**: Calculate potential savings with optimal method\n- **Recommendation Engine**: Provide intelligent recommendations with explanations\n\n## Method Details\n- **General Taxation**: Actual input/output method with precise tax calculations\n- **Simplified Taxation**: Business type-based deemed purchase rate method\n- **20% Special Rule**: Transitional measure paying 20% of output tax\n\n## Use Cases\n- **Tax Planning**: Plan optimal tax calculation method for upcoming periods\n- **Method Selection**: Choose between available calculation methods\n- **Savings Analysis**: Identify potential tax savings opportunities\n- **Compliance Planning**: Ensure optimal compliance with tax regulations\n- **Business Optimization**: Optimize tax burden through method selection\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Fiscal year for comparison",
            "in": "query",
            "name": "fiscal_year",
            "required": true,
            "schema": {
              "example": 2024,
              "type": "integer"
            }
          },
          {
            "description": "Period start date in YYYYMMDD format",
            "in": "query",
            "name": "period_start",
            "required": true,
            "schema": {
              "example": 20240101,
              "type": "integer"
            }
          },
          {
            "description": "Period end date in YYYYMMDD format",
            "in": "query",
            "name": "period_end",
            "required": true,
            "schema": {
              "example": 20241231,
              "type": "integer"
            }
          },
          {
            "description": "Business type for simplified taxation calculation",
            "in": "query",
            "name": "business_type",
            "required": false,
            "schema": {
              "$ref": "#/components/schemas/BusinessType"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MethodComparisonResponse"
                }
              }
            },
            "description": "Method comparison completed successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Compare calculation methods (計算方法比較)",
        "tags": [
          "Consumption Tax"
        ]
      }
    },
    "/consumption-tax/eligibility": {
      "get": {
        "description": "Check eligibility for simplified taxation based on base period sales.\n\n## Simplified Taxation Eligibility (簡易課税適用可否)\nEligibility assessment with:\n- **Base Period Analysis**: Analyze sales in the base period (2 years prior)\n- **Threshold Validation**: Check against ¥50,000,000 eligibility threshold\n- **Detailed Explanation**: Provide detailed explanation of eligibility status\n- **Legal Compliance**: Ensure compliance with simplified taxation requirements\n- **Planning Support**: Support tax planning and method selection decisions\n\n## Eligibility Criteria\n- **Base Period Sales**: Taxable sales in base period (基準期間の課税売上高)\n- **Threshold**: ¥50,000,000 annual sales threshold\n- **Base Period**: Two years prior to the current fiscal year\n- **Pre-Registration**: Requires advance notification to tax authorities\n- **Continuity**: Once selected, must continue for 2 years\n\n## Assessment Process\n1. **Base Period Identification**: Identify base period (2 years prior)\n2. **Sales Calculation**: Calculate total taxable sales for base period\n3. **Threshold Comparison**: Compare against ¥50,000,000 threshold\n4. **Eligibility Determination**: Determine eligibility status\n5. **Explanation Generation**: Generate detailed explanation\n\n## Use Cases\n- **Method Planning**: Plan calculation method for upcoming periods\n- **Eligibility Verification**: Verify eligibility before method selection\n- **Compliance Check**: Ensure compliance with eligibility requirements\n- **Tax Strategy**: Develop tax strategy based on eligibility status\n- **Advisory Services**: Provide advisory services to clients\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Fiscal year to check eligibility for",
            "in": "query",
            "name": "fiscal_year",
            "required": true,
            "schema": {
              "example": 2024,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/EligibilityResponse"
                }
              }
            },
            "description": "Eligibility check completed successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Check simplified taxation eligibility (簡易課税適用可否)",
        "tags": [
          "Consumption Tax"
        ]
      }
    },
    "/consumption-tax/health": {
      "get": {
        "description": "Check the health and availability of the Consumption Tax Return Support API.\n\n## Health Check Features\nAPI health monitoring with:\n- **Service Status**: Verify API service availability\n- **Feature Overview**: List available consumption tax calculation features\n- **System Information**: Basic system health information\n- **Compliance Readiness**: Verify tax calculation system readiness\n\n## Available Features\n- **General Taxation (一般課税)**: Standard input/output tax calculation method\n- **Simplified Taxation (簡易課税)**: Business type-based deemed purchase rate method\n- **20% Special Rule (2割特例)**: Special rule for new Invoice System registrants\n- **Method Comparison**: Compare all methods and provide optimization recommendations\n- **Quarterly Summary**: Quarterly tax calculation summaries for annual planning\n\n## Use Cases\n- **System Monitoring**: Monitor API health and availability\n- **Feature Discovery**: Discover available tax calculation features\n- **Integration Testing**: Test API connectivity and basic functionality\n- **Service Verification**: Verify service is ready for tax calculations\n\nNo authentication required for health check.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ConsumptionTaxHealthResponse"
                }
              }
            },
            "description": "API health check successful"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "Health check for Consumption Tax API",
        "tags": [
          "Consumption Tax"
        ]
      }
    },
    "/consumption-tax/preflight": {
      "get": {
        "description": "Run the integrity engine and return the findings that stand between the ledger and a correct 消費税申告書.\n\nMirrors the corporate gate at `GET /api/kakutei-shinkoku/preflight`. The FE renders blockers above the XTX button and disables generation while any remain.\n\n## Severity policy — fail-safe\nThe full COMPREHENSIVE suite runs, then rules that can only affect the 法人税 return (法人税等 provision, 別表, 定期同額給与, 均等割, 源泉, 減価償却タイミング) are demoted from ERROR to WARNING. Everything else blocks by default, so a newly added check can only over-block — never silently let a 消費税 error through.\n\nDeliberately blocking: 課税区分の不一致, 申告と帳簿の不一致, 税区分と科目の不一致, 前払分の仕入税額控除, インボイス経過措置漏れ, 課税売上割合ウォッチ, 二重計上, 円未満端数, 台帳キャッシュ乖離, 貸借不一致, 課税期間ズレ.\n\n## Unevaluated runs\n`runEvaluated: false` means the engine executed zero checks. `passed` is then always `false` and a `PREFLIGHT_ENGINE_UNEVALUATED` blocker is returned. An unevaluated ledger is not a clean ledger — on 2026-07-24 the engine returned zero checks for ~20h while the persisted run row still looked clean.\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "課税期間 (calendar year the period ends in). Defaults to the current year.",
            "in": "query",
            "name": "year",
            "required": false,
            "schema": {
              "example": 2026,
              "maximum": 2100,
              "minimum": 1900,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PreflightResponse"
                }
              }
            },
            "description": "Gate evaluated"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Pre-filing integrity gate for XTX generation (消費税申告前チェック)",
        "tags": [
          "Consumption Tax"
        ]
      }
    },
    "/consumption-tax/quarterly": {
      "get": {
        "description": "Get quarterly consumption tax summary for annual planning and cash flow management.\n\n## Quarterly Summary (四半期サマリー)\nComprehensive quarterly analysis with:\n- **Quarterly Breakdown**: Calculate tax amounts for each quarter of the fiscal year\n- **Annual Totals**: Aggregate quarterly amounts for annual planning\n- **Cash Flow Planning**: Support cash flow planning with quarterly tax estimates\n- **Trend Analysis**: Analyze quarterly trends and patterns\n- **Payment Planning**: Plan quarterly tax payments and cash requirements\n- **Compliance Monitoring**: Monitor quarterly compliance and obligations\n\n## Summary Information\n- **Quarter Details**: Start/end dates and tax calculations for each quarter\n- **Sales Tax**: Quarterly output tax amounts (仮受消費税)\n- **Purchase Tax**: Quarterly input tax amounts (仮払消費税)\n- **Estimated Tax Due**: Estimated quarterly tax payments\n- **Annual Totals**: Aggregated annual amounts for planning\n\n## Use Cases\n- **Annual Planning**: Plan annual tax obligations and cash flow\n- **Quarterly Payments**: Calculate quarterly tax payment requirements\n- **Cash Flow Management**: Manage cash flow for tax obligations\n- **Trend Analysis**: Analyze quarterly tax trends and patterns\n- **Compliance Planning**: Plan quarterly compliance activities\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Fiscal year for quarterly summary",
            "in": "query",
            "name": "fiscal_year",
            "required": true,
            "schema": {
              "example": 2024,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/QuarterlySummaryResponse"
                }
              }
            },
            "description": "Quarterly summary retrieved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get quarterly tax summary (四半期サマリー)",
        "tags": [
          "Consumption Tax"
        ]
      }
    },
    "/consumption-tax/reference/business-types": {
      "get": {
        "description": "Get reference information for business types used in simplified taxation.\n\n## Business Type Reference (事業区分参照)\nComprehensive business classification with:\n- **Six Business Types**: Complete classification system for simplified taxation\n- **Deemed Purchase Rates**: Official deemed purchase rates (みなし仕入率) for each type\n- **Detailed Descriptions**: Comprehensive descriptions of each business category\n- **Legal Framework**: Based on Japanese consumption tax law classifications\n- **Implementation Guidance**: Guidance for proper business type selection\n\n## Business Type Classifications\n- **Type 1 - Wholesale (第一種事業・卸売業)**: 90% deemed purchase rate\n  - Description: Sales to other businesses\n  - Examples: Wholesale distribution, B2B sales\n- **Type 2 - Retail (第二種事業・小売業)**: 80% deemed purchase rate\n  - Description: Sales to consumers\n  - Examples: Retail stores, consumer sales\n- **Type 3 - Manufacturing (第三種事業・製造業等)**: 70% deemed purchase rate\n  - Description: Agriculture, forestry, fishing, mining, construction, manufacturing, utilities\n  - Examples: Factories, construction companies, utilities\n- **Type 4 - Other (第四種事業・その他)**: 60% deemed purchase rate\n  - Description: Restaurants, financial services, insurance\n  - Examples: Dining establishments, banks, insurance companies\n- **Type 5 - Service (第五種事業・サービス業等)**: 50% deemed purchase rate\n  - Description: Transportation, communications, services (excluding restaurants)\n  - Examples: Consulting, IT services, transportation\n- **Type 6 - Real Estate (第六種事業・不動産業)**: 40% deemed purchase rate\n  - Description: Real estate business\n  - Examples: Property sales, real estate management\n\n## Reference Information\n- **Legal Basis**: Based on Japanese Consumption Tax Law\n- **Selection Criteria**: Guidance for selecting appropriate business type\n- **Implementation Notes**: Important notes for simplified taxation selection\n- **Compliance Requirements**: Requirements for using simplified taxation\n\n## Use Cases\n- **Business Classification**: Classify business for simplified taxation\n- **Rate Determination**: Determine appropriate deemed purchase rate\n- **Method Selection**: Support simplified taxation method selection\n- **Compliance Planning**: Plan compliance with business type requirements\n- **Advisory Services**: Provide business classification advisory services\n\nNo authentication required for reference data.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BusinessTypeReferenceResponse"
                }
              }
            },
            "description": "Business type reference retrieved successfully"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "Get business type reference (事業区分参照)",
        "tags": [
          "Consumption Tax"
        ]
      }
    },
    "/consumption-tax/reference/calculation-methods": {
      "get": {
        "description": "Get reference information for consumption tax calculation methods.\n\n## Calculation Method Reference (計算方法参照)\nComprehensive method information with:\n- **Three Methods**: Complete information for all calculation methods\n- **Requirements**: Detailed requirements for each method\n- **Advantages/Disadvantages**: Pros and cons of each method\n- **Legal Framework**: Based on Japanese consumption tax law\n- **Selection Guidance**: Guidance for method selection and optimization\n\n## Method Details\n- **General Taxation (一般課税・本則課税)**:\n  - Description: Standard method using actual input and output tax\n  - Requirements: No special requirements (default method)\n  - Advantages: Accurate reflection of actual purchases, beneficial when input tax is high\n  - Disadvantages: Complex bookkeeping, invoice preservation required\n- **Simplified Taxation (簡易課税)**:\n  - Description: Uses business type-based deemed purchase rates\n  - Requirements: Base period sales ≤ ¥50,000,000, advance notification required\n  - Advantages: Simplified bookkeeping, beneficial for low-purchase businesses\n  - Disadvantages: Cannot deduct actual high purchases, 2-year commitment\n- **20% Special Rule (2割特例)**:\n  - Description: Pay 20% of output tax (transitional measure)\n  - Requirements: New registrants due to Invoice System\n  - Advantages: Simplest calculation, often most beneficial\n  - Disadvantages: Limited to eligible businesses, expires September 30, 2026\n\n## Reference Information\n- **Legal Basis**: Japanese Consumption Tax Law provisions\n- **Selection Criteria**: Criteria for optimal method selection\n- **Compliance Notes**: Important compliance considerations\n- **Planning Guidance**: Strategic planning considerations for each method\n\n## Use Cases\n- **Method Education**: Educate users about available calculation methods\n- **Selection Support**: Support method selection decisions\n- **Compliance Planning**: Plan compliance with method requirements\n- **Strategic Planning**: Develop tax strategy based on method characteristics\n- **Advisory Services**: Provide method selection advisory services\n\nNo authentication required for reference data.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CalculationMethodReferenceResponse"
                }
              }
            },
            "description": "Calculation method reference retrieved successfully"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "Get calculation method reference (計算方法参照)",
        "tags": [
          "Consumption Tax"
        ]
      }
    },
    "/corporate-registry/health-check": {
      "get": {
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "checks": {
                          "items": {
                            "$ref": "#/components/schemas/RegistryHealthCheck"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Health check results"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "登記ヘルスチェック — director term, みなし解散, 決算公告",
        "tags": [
          "Corporate Registry"
        ]
      }
    },
    "/corporate-registry/profile": {
      "get": {
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CorporateRegistryProfile"
                }
              }
            },
            "description": "Profile or null"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get corporate registry profile",
        "tags": [
          "Corporate Registry"
        ]
      },
      "put": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CorporateRegistryProfile"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Upserted"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Upsert corporate registry profile",
        "tags": [
          "Corporate Registry"
        ]
      }
    },
    "/cron/bank-sync": {
      "get": {
        "description": "EventBridge GET. Auth: x-cron-secret. Not a product API.",
        "responses": {
          "200": {
            "description": "Job completed"
          },
          "401": {
            "description": "Missing or invalid cron secret"
          }
        },
        "summary": "EventBridge bank-sync job (internal)",
        "tags": [
          "Cron Jobs"
        ],
        "x-internal": true
      }
    },
    "/cron/cleanup": {
      "get": {
        "description": "EventBridge GET. Auth: x-cron-secret. Not a product API.",
        "responses": {
          "200": {
            "description": "Job completed"
          },
          "401": {
            "description": "Missing or invalid cron secret"
          }
        },
        "summary": "EventBridge cleanup job (internal)",
        "tags": [
          "Cron Jobs"
        ],
        "x-internal": true
      }
    },
    "/cron/cleanup-lp-demos": {
      "get": {
        "description": "EventBridge GET. Auth: x-cron-secret. Not a product API.",
        "responses": {
          "200": {
            "description": "Job completed"
          },
          "401": {
            "description": "Missing or invalid cron secret"
          }
        },
        "summary": "EventBridge cleanup-lp-demos job (internal)",
        "tags": [
          "Cron Jobs"
        ],
        "x-internal": true
      }
    },
    "/cron/compliance-rule-engine": {
      "get": {
        "description": "EventBridge GET. Auth: x-cron-secret. Not a product API.",
        "responses": {
          "200": {
            "description": "Job completed"
          },
          "401": {
            "description": "Missing or invalid cron secret"
          }
        },
        "summary": "EventBridge compliance-rule-engine job (internal)",
        "tags": [
          "Cron Jobs"
        ],
        "x-internal": true
      }
    },
    "/cron/deadline-recompute": {
      "get": {
        "description": "EventBridge GET. Auth: x-cron-secret. Not a product API.",
        "responses": {
          "200": {
            "description": "Job completed"
          },
          "401": {
            "description": "Missing or invalid cron secret"
          }
        },
        "summary": "EventBridge deadline-recompute job (internal)",
        "tags": [
          "Cron Jobs"
        ],
        "x-internal": true
      }
    },
    "/cron/depreciation": {
      "get": {
        "description": "EventBridge GET (daily in AWS). Auth: x-cron-secret. Not a product API.",
        "responses": {
          "200": {
            "description": "Job completed"
          },
          "401": {
            "description": "Missing or invalid cron secret"
          }
        },
        "summary": "EventBridge depreciation job (internal)",
        "tags": [
          "Cron Jobs"
        ],
        "x-internal": true
      }
    },
    "/cron/depreciation/trigger": {
      "post": {
        "description": "Manually trigger the monthly depreciation calculation job for testing and administrative purposes.\n\n## Depreciation Job (減価償却ジョブ)\nAutomated fixed asset depreciation with:\n- **Monthly Calculation**: Calculate depreciation for all active fixed assets\n- **Journal Entry Creation**: Generate journal entries for depreciation expense\n- **Asset Book Value Update**: Update closing book values for all assets\n- **Multiple Methods**: Support for straight-line and declining balance methods\n- **Duplicate Prevention**: Prevent duplicate depreciation entries for same period\n\n## Job Execution Process\n1. **Asset Retrieval**: Retrieve all active fixed assets (excluding land)\n2. **Depreciation Calculation**: Calculate monthly depreciation using configured method\n3. **Journal Entry Creation**: Create journal entries for depreciation expense and accumulated depreciation\n4. **Book Value Update**: Update asset closing book values\n5. **Audit Logging**: Log all depreciation calculations and journal entries\n\n## Depreciation Methods Supported\n- **Straight-Line Method (定額法)**: Equal depreciation amounts over useful life\n- **Declining Balance Method (定率法)**: Higher depreciation in early years\n- **Old Methods**: Support for legacy depreciation methods\n- **Asset-Specific**: Different methods per asset classification\n\n## Manual Trigger Benefits\n- **Testing**: Test depreciation calculations in development environment\n- **Month-End Processing**: Force depreciation calculation for month-end closing\n- **Data Correction**: Recalculate depreciation after asset updates\n- **Administrative Control**: Manual control over depreciation timing\n- **Troubleshooting**: Diagnose depreciation calculation issues\n\n## Use Cases\n- **Development Testing**: Test depreciation functionality during development\n- **Month-End Closing**: Manual depreciation calculation for accounting periods\n- **Asset Management**: Recalculate depreciation after asset changes\n- **Data Validation**: Validate depreciation calculations and journal entries\n- **System Maintenance**: Perform maintenance-related depreciation updates\n\n## Authentication\nRequires valid Bearer token in Authorization header with administrative privileges.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful_execution": {
                    "summary": "Successful depreciation job",
                    "value": {
                      "data": {
                        "endTime": "2024-01-01T02:00:15.000Z",
                        "errors": [],
                        "executionTime": 15000,
                        "jobName": "depreciation",
                        "result": {
                          "assetsProcessed": 25,
                          "journalEntriesCreated": 25,
                          "methodsUsed": [
                            "straight_line",
                            "declining_balance"
                          ],
                          "totalDepreciationAmount": 125000
                        },
                        "startTime": "2024-01-01T02:00:00.000Z",
                        "success": true
                      },
                      "message": "Job executed successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/JobTriggerResponse"
                }
              }
            },
            "description": "Depreciation job executed successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Manual cron triggers are not allowed in production environment",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Manual triggers not allowed in production environment"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Manually trigger depreciation job",
        "tags": [
          "Cron Jobs"
        ],
        "x-internal": true
      }
    },
    "/cron/exchange-rate": {
      "get": {
        "description": "EventBridge GET. Auth: x-cron-secret. Not a product API.",
        "responses": {
          "200": {
            "description": "Job completed"
          },
          "401": {
            "description": "Missing or invalid cron secret"
          }
        },
        "summary": "EventBridge exchange-rate job (internal)",
        "tags": [
          "Cron Jobs"
        ],
        "x-internal": true
      }
    },
    "/cron/exchange-rate/trigger": {
      "post": {
        "description": "Manually trigger the daily exchange rate fetching job for testing and administrative purposes.\n\n## Exchange Rate Job (為替レート取得ジョブ)\nAutomated exchange rate management with:\n- **Daily Rate Fetching**: Retrieve current exchange rates from external APIs\n- **Multi-Currency Support**: Fetch rates for all supported currency pairs\n- **Database Caching**: Store rates in local database for fast access\n- **Error Handling**: Comprehensive error handling for API failures\n- **Audit Trail**: Complete logging of rate fetching operations\n\n## Job Execution Process\n1. **External API Call**: Fetch current rates from configured providers\n2. **Data Validation**: Validate fetched rates for accuracy and completeness\n3. **Database Update**: Update local cache with fresh exchange rate data\n4. **Error Handling**: Handle API failures and data validation errors\n5. **Audit Logging**: Log execution results and any issues encountered\n\n## Manual Trigger Benefits\n- **Testing**: Test exchange rate fetching in development environment\n- **Data Refresh**: Force refresh of exchange rates when needed\n- **Troubleshooting**: Diagnose exchange rate fetching issues\n- **Administrative Control**: Manual control over rate updates\n- **Emergency Updates**: Update rates outside normal schedule if needed\n\n## Environment Restrictions\n- **Development/Staging**: Manual triggers available for testing\n- **Production**: Manual triggers disabled for safety and stability\n- **Authentication**: Requires administrative authentication\n- **Rate Limiting**: Protected against abuse with proper rate limiting\n\n## Use Cases\n- **Development Testing**: Test exchange rate functionality during development\n- **Data Validation**: Validate exchange rate fetching and storage\n- **Troubleshooting**: Diagnose and resolve rate fetching issues\n- **Emergency Updates**: Update rates outside normal schedule\n- **System Maintenance**: Perform maintenance-related rate updates\n\n## Authentication\nRequires valid Bearer token in Authorization header with administrative privileges.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful_execution": {
                    "summary": "Successful job execution",
                    "value": {
                      "data": {
                        "endTime": "2024-01-15T04:00:02.500Z",
                        "errors": [],
                        "executionTime": 2500,
                        "jobName": "exchange-rate",
                        "result": {
                          "cacheUpdated": true,
                          "currenciesProcessed": [
                            "USD",
                            "EUR",
                            "GBP",
                            "CNY",
                            "KRW"
                          ],
                          "provider": "fixer.io",
                          "ratesUpdated": 15
                        },
                        "startTime": "2024-01-15T04:00:00.000Z",
                        "success": true
                      },
                      "message": "Job executed successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/JobTriggerResponse"
                }
              }
            },
            "description": "Exchange rate job executed successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Manual cron triggers are not allowed in production environment",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Manual triggers not allowed in production environment"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Manually trigger exchange rate job",
        "tags": [
          "Cron Jobs"
        ],
        "x-internal": true
      }
    },
    "/cron/family-hiring-monitor": {
      "get": {
        "description": "EventBridge GET. Auth: x-cron-secret. Not a product API.",
        "responses": {
          "200": {
            "description": "Job completed"
          },
          "401": {
            "description": "Missing or invalid cron secret"
          }
        },
        "summary": "EventBridge family-hiring-monitor job (internal)",
        "tags": [
          "Cron Jobs"
        ],
        "x-internal": true
      }
    },
    "/cron/insights": {
      "get": {
        "description": "EventBridge GET. Auth: x-cron-secret. Not a product API.",
        "responses": {
          "200": {
            "description": "Job completed"
          },
          "401": {
            "description": "Missing or invalid cron secret"
          }
        },
        "summary": "EventBridge insights job (internal)",
        "tags": [
          "Cron Jobs"
        ],
        "x-internal": true
      }
    },
    "/cron/insights-weekly": {
      "get": {
        "description": "EventBridge GET. Auth: x-cron-secret. Not a product API.",
        "responses": {
          "200": {
            "description": "Job completed"
          },
          "401": {
            "description": "Missing or invalid cron secret"
          }
        },
        "summary": "EventBridge insights-weekly job (internal)",
        "tags": [
          "Cron Jobs"
        ],
        "x-internal": true
      }
    },
    "/cron/integration-pull": {
      "get": {
        "description": "Money-ecosystem pull sources (BE ADR-0021): tsumagoi batches → drafts, yen-yen → 立替 claims, C3 pushes, payout auto-match, alerts. EventBridge GET. Auth: x-cron-secret. Not a product API.",
        "responses": {
          "200": {
            "description": "Job completed"
          },
          "401": {
            "description": "Missing or invalid cron secret"
          }
        },
        "summary": "EventBridge integration-pull job (internal)",
        "tags": [
          "Cron Jobs"
        ],
        "x-internal": true
      }
    },
    "/cron/integrity-check": {
      "get": {
        "description": "EventBridge GET. Auth: x-cron-secret. Not a product API.",
        "responses": {
          "200": {
            "description": "Job completed"
          },
          "401": {
            "description": "Missing or invalid cron secret"
          }
        },
        "summary": "EventBridge integrity-check job (internal)",
        "tags": [
          "Cron Jobs"
        ],
        "x-internal": true
      }
    },
    "/cron/ledger-sync": {
      "get": {
        "description": "EventBridge GET. Auth: x-cron-secret. Not a product API.",
        "responses": {
          "200": {
            "description": "Job completed"
          },
          "401": {
            "description": "Missing or invalid cron secret"
          }
        },
        "summary": "EventBridge ledger-sync job (internal)",
        "tags": [
          "Cron Jobs"
        ],
        "x-internal": true
      }
    },
    "/cron/lifecycle-email": {
      "get": {
        "description": "EventBridge GET, daily 00:00 UTC (09:00 JST). GTM Phase 2 onboarding nudges: day-2 import nudge and day-7 activation nudge, deduped through notification_deliveries. `?dryRun=1` reports cohorts without sending. Auth: x-cron-secret. Not a product API.",
        "responses": {
          "200": {
            "description": "Job completed (stats in data)"
          },
          "401": {
            "description": "Missing or invalid cron secret"
          }
        },
        "summary": "EventBridge lifecycle-email job (internal)",
        "tags": [
          "Cron Jobs"
        ],
        "x-internal": true
      }
    },
    "/cron/logs": {
      "get": {
        "description": "Retrieve comprehensive cron job execution logs for monitoring, troubleshooting, and audit purposes.\n\n## Execution Log Monitoring\nComprehensive logging information including:\n- **Execution History**: Complete history of all cron job executions\n- **Success/Failure Tracking**: Status tracking for all job executions\n- **Performance Metrics**: Execution duration and performance analysis\n- **Error Documentation**: Detailed error logs for troubleshooting\n- **Administrative Audit**: Complete audit trail for administrative review\n\n## Log Information\n- **Job Identification**: Clear identification of executed jobs\n- **Execution Type**: Distinction between scheduled and manual executions\n- **Timing Information**: Start time, end time, and duration tracking\n- **Result Details**: Detailed results and processing statistics\n- **Error Tracking**: Comprehensive error logging and analysis\n\n## Use Cases\n- **System Monitoring**: Monitor cron job execution health and performance\n- **Troubleshooting**: Diagnose and resolve job execution issues\n- **Performance Analysis**: Analyze job performance and optimization opportunities\n- **Audit Review**: Review execution history for compliance and audit\n- **Administrative Oversight**: Administrative monitoring of scheduled operations\n\n## Log Filtering\n- **Job Type Filtering**: Filter logs by specific job types\n- **Date Range Filtering**: Filter logs by execution date range\n- **Status Filtering**: Filter by execution status (success, failure, partial)\n- **Performance Analysis**: Filter by execution duration for performance review\n\n## Authentication\nRequires valid Bearer token in Authorization header with administrative privileges.",
        "parameters": [
          {
            "description": "Filter logs by specific job name",
            "example": "exchange-rate",
            "in": "query",
            "name": "job_name",
            "required": false,
            "schema": {
              "enum": [
                "exchange-rate",
                "depreciation",
                "trial-balance"
              ],
              "type": "string"
            }
          },
          {
            "description": "Start date for log filtering",
            "example": "2024-01-01T00:00:00.000Z",
            "in": "query",
            "name": "start_date",
            "required": false,
            "schema": {
              "format": "date-time",
              "type": "string"
            }
          },
          {
            "description": "End date for log filtering",
            "example": "2024-01-31T23:59:59.999Z",
            "in": "query",
            "name": "end_date",
            "required": false,
            "schema": {
              "format": "date-time",
              "type": "string"
            }
          },
          {
            "description": "Filter logs by execution status",
            "example": "success",
            "in": "query",
            "name": "status",
            "required": false,
            "schema": {
              "enum": [
                "success",
                "failure",
                "partial"
              ],
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "execution_logs": {
                    "summary": "Recent execution logs",
                    "value": {
                      "data": [
                        {
                          "duration": 2500,
                          "endTime": "2024-01-15T04:00:02.500Z",
                          "errors": [],
                          "executionType": "scheduled",
                          "id": "123e4567-e89b-12d3-a456-426614174000",
                          "jobName": "exchange-rate",
                          "recordsProcessed": 15,
                          "startTime": "2024-01-15T04:00:00.000Z",
                          "status": "success",
                          "triggeredBy": null
                        },
                        {
                          "duration": 15000,
                          "endTime": "2024-01-01T02:00:15.000Z",
                          "errors": [],
                          "executionType": "manual",
                          "id": "456e7890-f12a-34b5-c678-901234567890",
                          "jobName": "depreciation",
                          "recordsProcessed": 25,
                          "startTime": "2024-01-01T02:00:00.000Z",
                          "status": "success",
                          "triggeredBy": "abc12345-def6-7890-ghij-klmnopqrstuv"
                        },
                        {
                          "duration": 8500,
                          "endTime": "2024-01-25T01:00:08.500Z",
                          "errors": [
                            "User ID xyz: insufficient data for trial balance generation"
                          ],
                          "executionType": "scheduled",
                          "id": "789e0123-e45b-67c8-d901-234567890123",
                          "jobName": "trial-balance",
                          "recordsProcessed": 14,
                          "startTime": "2024-01-25T01:00:00.000Z",
                          "status": "partial",
                          "triggeredBy": null
                        }
                      ],
                      "message": "Cron logs retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/CronLogsResponse"
                }
              }
            },
            "description": "Cron logs retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Administrative privileges required for cron log access",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Insufficient privileges for log access"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get cron job execution logs",
        "tags": [
          "Cron Jobs"
        ],
        "x-internal": true
      }
    },
    "/cron/official-rules-refresh": {
      "get": {
        "description": "EventBridge GET. Auth: x-cron-secret. Not a product API.",
        "responses": {
          "200": {
            "description": "Job completed"
          },
          "401": {
            "description": "Missing or invalid cron secret"
          }
        },
        "summary": "EventBridge official-rules-refresh job (internal)",
        "tags": [
          "Cron Jobs"
        ],
        "x-internal": true
      }
    },
    "/cron/recover-jobs": {
      "get": {
        "description": "EventBridge GET crontab cron(0/10 * * * ? *). Auth: x-cron-secret. Reclaims stuck queue jobs, drains founding alerts, and heals the file search index (≤25 files, no new file after 20 s; counts in data.fileSearchSweep). Not a product API.",
        "responses": {
          "200": {
            "description": "Recovery pass completed"
          },
          "401": {
            "description": "Missing or invalid cron secret"
          }
        },
        "summary": "EventBridge recover-jobs (internal)",
        "tags": [
          "Cron Jobs"
        ],
        "x-internal": true
      }
    },
    "/cron/status": {
      "get": {
        "description": "Retrieve comprehensive cron job configuration, status, and availability information for administrative monitoring.\n\n## Cron Job Status Overview\nComprehensive status information including:\n- **Configuration Details**: Current cron configuration and environment settings\n- **Job Availability**: List of all available cron jobs with schedules and status\n- **Environment Information**: Current environment and execution context\n- **Manual Trigger Availability**: Whether manual triggers are available\n- **Security Configuration**: Cron secret and authentication status\n\n## Available Cron Jobs\nProduction EventBridge GET jobs (x-cron-secret; see tag description). Status here reports local node-cron enable flags — schedules in this payload are not the AWS SoT.\n\n## Configuration Information\n- **Environment**: Current execution environment (development, staging, production)\n- **Timezone**: Local node-cron uses Asia/Tokyo; EventBridge expressions are UTC\n- **Auto-Start**: Whether jobs automatically start on application startup (local only)\n- **Serverless Mode**: Whether running in serverless environment\n- **Job Status**: Individual enable/disable status for each job\n\n## Manual Trigger Controls\n- **Development/Staging**: Manual triggers available for testing\n- **Production**: Manual triggers disabled for safety\n- **Authentication**: Requires administrative authentication\n- **Audit Trail**: Complete logging of manual trigger usage\n\n## Use Cases\n- **System Monitoring**: Monitor cron job configuration and status\n- **Administrative Overview**: Get complete system job status\n- **Troubleshooting**: Diagnose job configuration and availability issues\n- **Environment Validation**: Verify proper job configuration for environment\n- **Security Audit**: Review job security and access configuration\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "development_status": {
                    "summary": "Development environment status",
                    "value": {
                      "data": {
                        "availableJobs": [
                          {
                            "description": "Daily exchange rate fetching job",
                            "enabled": true,
                            "name": "exchange-rate",
                            "schedule": "0 4 * * * (4:00 AM JST)"
                          },
                          {
                            "description": "Monthly depreciation calculation job",
                            "enabled": true,
                            "name": "depreciation",
                            "schedule": "0 2 1 * * (2:00 AM JST on 1st of month)"
                          },
                          {
                            "description": "Monthly trial balance generation job",
                            "enabled": true,
                            "name": "trial-balance",
                            "schedule": "0 1 25 * * (1:00 AM JST on 25th of month)"
                          }
                        ],
                        "configuration": {
                          "autoStart": true,
                          "cronSecret": "configured",
                          "environment": "development",
                          "isServerless": false,
                          "jobsEnabled": {
                            "DEPRECIATION": true,
                            "EXCHANGE_RATE": true,
                            "TRIAL_BALANCE": true
                          },
                          "timezone": "Asia/Tokyo"
                        },
                        "manualTriggers": {
                          "available": true,
                          "note": "Manual triggers are only available in development and staging"
                        }
                      },
                      "message": "Cron status retrieved successfully",
                      "statusCode": 200
                    }
                  },
                  "production_status": {
                    "summary": "Production environment status",
                    "value": {
                      "data": {
                        "availableJobs": [
                          {
                            "description": "Daily exchange rate fetching job",
                            "enabled": true,
                            "name": "exchange-rate",
                            "schedule": "0 4 * * * (4:00 AM JST)"
                          },
                          {
                            "description": "Monthly depreciation calculation job",
                            "enabled": true,
                            "name": "depreciation",
                            "schedule": "0 2 1 * * (2:00 AM JST on 1st of month)"
                          },
                          {
                            "description": "Monthly trial balance generation job",
                            "enabled": true,
                            "name": "trial-balance",
                            "schedule": "0 1 25 * * (1:00 AM JST on 25th of month)"
                          }
                        ],
                        "configuration": {
                          "autoStart": false,
                          "cronSecret": "configured",
                          "environment": "production",
                          "isServerless": true,
                          "jobsEnabled": {
                            "DEPRECIATION": true,
                            "EXCHANGE_RATE": true,
                            "TRIAL_BALANCE": true
                          },
                          "timezone": "Asia/Tokyo"
                        },
                        "manualTriggers": {
                          "available": false,
                          "note": "Manual triggers are only available in development and staging"
                        }
                      },
                      "message": "Cron status retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/CronStatusResponse"
                }
              }
            },
            "description": "Cron status retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get cron job status and configuration",
        "tags": [
          "Cron Jobs"
        ],
        "x-internal": true
      }
    },
    "/cron/stripe-payout-sync": {
      "get": {
        "description": "Stripe payouts of the shared account → draft entries (BE ADR-0021). EventBridge GET. Auth: x-cron-secret. Not a product API.",
        "responses": {
          "200": {
            "description": "Job completed"
          },
          "401": {
            "description": "Missing or invalid cron secret"
          }
        },
        "summary": "EventBridge stripe-payout-sync job (internal)",
        "tags": [
          "Cron Jobs"
        ],
        "x-internal": true
      }
    },
    "/cron/trial-balance": {
      "get": {
        "description": "EventBridge GET (daily in AWS). Auth: x-cron-secret. Not a product API.",
        "responses": {
          "200": {
            "description": "Job completed"
          },
          "401": {
            "description": "Missing or invalid cron secret"
          }
        },
        "summary": "EventBridge trial-balance job (internal)",
        "tags": [
          "Cron Jobs"
        ],
        "x-internal": true
      }
    },
    "/cron/trial-balance/trigger": {
      "post": {
        "description": "Manually trigger the monthly trial balance generation job for testing and administrative purposes.\n\n## Trial Balance Job (試算表生成ジョブ)\nAutomated trial balance generation with:\n- **Monthly Generation**: Generate trial balance for all users on 25th of each month\n- **Period Analysis**: Calculate trial balance for previous month period\n- **Account Balancing**: Ensure all accounts are properly balanced\n- **Multi-User Processing**: Process trial balance for all active users\n- **Error Resilience**: Continue processing even if individual users fail\n\n## Job Execution Process\n1. **User Retrieval**: Get all active users in the system\n2. **Period Calculation**: Calculate previous month date range\n3. **Trial Balance Generation**: Generate trial balance for each user\n4. **Balance Validation**: Verify trial balance integrity and accuracy\n5. **Error Handling**: Handle individual user failures gracefully\n\n## Trial Balance Features\n- **Double-Entry Validation**: Ensure all trial balances are properly balanced\n- **Account Categorization**: Organize accounts by type (asset, liability, equity, revenue, expense)\n- **Opening/Closing Balances**: Track opening, period activity, and closing balances\n- **Japanese Format**: Generate trial balance in standard Japanese format\n- **Audit Compliance**: Trial balance ready for audit and compliance review\n\n## Manual Trigger Benefits\n- **Testing**: Test trial balance generation in development environment\n- **Month-End Processing**: Force trial balance generation for accounting periods\n- **Data Validation**: Validate trial balance calculations and accuracy\n- **Administrative Control**: Manual control over trial balance timing\n- **Troubleshooting**: Diagnose trial balance generation issues\n\n## Use Cases\n- **Development Testing**: Test trial balance functionality during development\n- **Month-End Closing**: Manual trial balance generation for accounting periods\n- **Data Validation**: Validate trial balance accuracy and completeness\n- **System Maintenance**: Perform maintenance-related trial balance updates\n- **Audit Preparation**: Generate trial balance for audit preparation\n\n## Authentication\nRequires valid Bearer token in Authorization header with administrative privileges.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful_execution": {
                    "summary": "Successful trial balance job",
                    "value": {
                      "data": {
                        "endTime": "2024-01-25T01:00:08.500Z",
                        "errors": [],
                        "executionTime": 8500,
                        "jobName": "trial-balance",
                        "result": {
                          "balanceValidation": "all_balanced",
                          "totalAccounts": 375,
                          "trialBalancesGenerated": 15,
                          "usersProcessed": 15
                        },
                        "startTime": "2024-01-25T01:00:00.000Z",
                        "success": true
                      },
                      "message": "Job executed successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/JobTriggerResponse"
                }
              }
            },
            "description": "Trial balance job executed successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Manual cron triggers are not allowed in production environment",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Manual triggers not allowed in production environment"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Manually trigger trial balance job",
        "tags": [
          "Cron Jobs"
        ],
        "x-internal": true
      }
    },
    "/cron/warm": {
      "get": {
        "description": "EventBridge GET every 5 minutes. Auth: x-cron-secret. Runs SELECT 1, re-opens this environment’s warm connections, reports the session statement_timeout, and fans out KEEP_WARM_CONCURRENCY-1 secret-bearing /health pings so the other environments re-warm too. Not a product API.",
        "responses": {
          "200": {
            "description": "Warm ping completed"
          },
          "401": {
            "description": "Missing or invalid cron secret"
          }
        },
        "summary": "EventBridge keep-warm (internal)",
        "tags": [
          "Cron Jobs"
        ],
        "x-internal": true
      }
    },
    "/cron/webhook/bulk-upload-process": {
      "post": {
        "description": "Self-invoked by this Lambda (lambda:InvokeFunction on itself, policy sbc-backend-self-invoke) after POST /bulk-upload/upload, after a single file upload, and by the progress / SSE watchdogs. Auth: x-cron-secret. Claims the scope’s pending rows one conditional UPDATE at a time, runs each under a 90 s deadline, writes the outcome back (background_jobs, session_files, SSE), and returns once every claimed row is written. Not a product API — see docs/ops-bulk-upload-worker.md.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "dispatched_at": {
                    "format": "date-time",
                    "type": "string"
                  },
                  "job_ids": {
                    "items": {
                      "type": "string"
                    },
                    "maxItems": 100,
                    "type": "array"
                  },
                  "kind": {
                    "enum": [
                      "bulk-upload",
                      "file-analyze"
                    ],
                    "type": "string"
                  },
                  "lease": {
                    "description": "cron_run_locks holder token the worker releases when done",
                    "type": "string"
                  },
                  "session_id": {
                    "description": "bulk-upload: the upload session",
                    "type": "string"
                  },
                  "user_id": {
                    "type": "string"
                  }
                },
                "required": [
                  "kind",
                  "user_id",
                  "dispatched_at"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "completed": {
                          "type": "integer"
                        },
                        "failed": {
                          "type": "integer"
                        },
                        "outstanding": {
                          "type": "integer"
                        },
                        "retrying": {
                          "type": "integer"
                        }
                      },
                      "required": [
                        "completed",
                        "failed",
                        "retrying",
                        "outstanding"
                      ],
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Worker finished"
          },
          "400": {
            "description": "Invalid worker payload"
          },
          "401": {
            "description": "Missing or invalid cron secret"
          }
        },
        "summary": "Lambda job worker: bulk-upload and file-analyze background_jobs (internal)",
        "tags": [
          "Cron Jobs"
        ],
        "x-internal": true
      }
    },
    "/database-docs": {
      "get": {
        "description": "Retrieves complete database schema documentation including models, enums, configuration, and statistics.\n      \n## Database Documentation Overview\n- **Complete Schema**: All database models with fields, relations, and metadata\n- **Categorized Models**: Models organized by business domain (Core, Business, System)\n- **Enum Definitions**: All database enums with values and descriptions\n- **Supabase Integration**: Configuration and feature documentation\n- **Environment Setup**: Required environment variables and configuration\n- **Real-time Statistics**: Current database metrics and counts\n\n## Schema Information\n- **Model Definitions**: Complete table structures with field types and constraints\n- **Relationship Mapping**: Foreign key relationships and cardinality\n- **Index Information**: Database indexes for performance optimization\n- **Category Organization**: Business logic grouping of related models\n\n## Configuration Details\n- **Supabase Features**: RLS, Auth, Storage, and other feature configurations\n- **Environment Variables**: Required and optional configuration variables\n- **Integration Points**: External service connections and API configurations\n- **Security Settings**: Authentication and authorization configurations\n\n## Use Cases\n- **API Documentation**: Complete reference for database structure\n- **Frontend Development**: Schema information for type generation\n- **Database Migration**: Understanding current schema for changes\n- **System Integration**: Reference for external system connections",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-retrieval": {
                    "summary": "Successful database documentation retrieval",
                    "value": {
                      "data": {
                        "enums": [
                          {
                            "description": "Document status values",
                            "name": "document_status",
                            "values": [
                              "DRAFT",
                              "PUBLISHED",
                              "ARCHIVED"
                            ]
                          }
                        ],
                        "envVariables": {
                          "database": {
                            "SUPABASE_ANON_KEY": "Supabase anonymous key",
                            "SUPABASE_URL": "Supabase project URL"
                          }
                        },
                        "models": [
                          {
                            "category": "Core",
                            "description": "User accounts with preferences and authentication data",
                            "displayName": "User Profiles",
                            "fields": [
                              {
                                "description": "Primary key",
                                "name": "id",
                                "nullable": false,
                                "type": "UUID"
                              },
                              {
                                "description": "User email",
                                "name": "email",
                                "nullable": true,
                                "type": "String"
                              }
                            ],
                            "name": "user_profiles",
                            "relations": [
                              {
                                "name": "companies",
                                "relatedModel": "companies",
                                "type": "one-to-many"
                              }
                            ]
                          }
                        ],
                        "modelsByCategory": {
                          "Core": [
                            {
                              "category": "Core",
                              "description": "User accounts with preferences and authentication data",
                              "displayName": "User Profiles",
                              "fields": [],
                              "name": "user_profiles",
                              "relations": []
                            }
                          ]
                        },
                        "stats": {
                          "categories": [
                            "Core",
                            "Business",
                            "System"
                          ],
                          "totalEnums": 8,
                          "totalFields": 120,
                          "totalModels": 15,
                          "totalRelations": 45
                        },
                        "supabaseConfig": [
                          {
                            "description": "Database-level security policies",
                            "envVar": "SUPABASE_URL",
                            "feature": "Row Level Security"
                          }
                        ]
                      },
                      "message": "Database documentation retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/DatabaseDocsResponse"
                }
              }
            },
            "description": "Database documentation retrieved successfully"
          },
          "500": {
            "content": {
              "application/json": {
                "examples": {
                  "service-error": {
                    "summary": "Database service error",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "Failed to retrieve database documentation",
                      "statusCode": 500
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error"
          }
        },
        "summary": "Get comprehensive database documentation",
        "tags": [
          "Database Documentation"
        ]
      }
    },
    "/database-docs/enums": {
      "get": {
        "description": "Retrieves all database enum definitions with values and descriptions.\n      \n## Enum Information\n- **Enum Names**: Database enum type names\n- **Value Lists**: All possible enum values\n- **Descriptions**: Purpose and usage of each enum\n- **Type Safety**: Ensures consistent value usage across the application\n\n## Common Enums\n- **Status Enums**: Document status, user status, processing status\n- **Type Enums**: File types, notification types, payment types\n- **Category Enums**: Business categories, expense categories\n- **Permission Enums**: User roles, access levels, feature permissions\n\n## Integration Points\n- **Database Constraints**: Enforced at database level for data integrity\n- **API Validation**: Used in request/response validation\n- **Frontend Types**: Generated TypeScript enums for type safety\n- **Business Logic**: Consistent status and type handling\n\n## Use Cases\n- **Type Generation**: Frontend enum generation for TypeScript\n- **Validation**: API request validation and database constraints\n- **UI Components**: Dropdown options and status displays\n- **Business Logic**: Consistent status and workflow management",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-enums-retrieval": {
                    "summary": "Successful database enums retrieval",
                    "value": {
                      "data": [
                        {
                          "description": "Status values for document processing workflow",
                          "name": "document_status",
                          "values": [
                            "DRAFT",
                            "PROCESSING",
                            "COMPLETED",
                            "FAILED",
                            "ARCHIVED"
                          ]
                        },
                        {
                          "description": "Supported file types for document uploads",
                          "name": "file_type",
                          "values": [
                            "PDF",
                            "IMAGE",
                            "SPREADSHEET",
                            "TEXT",
                            "OTHER"
                          ]
                        },
                        {
                          "description": "Categories for expense classification",
                          "name": "expense_category",
                          "values": [
                            "OFFICE_SUPPLIES",
                            "TRAVEL",
                            "MEALS",
                            "UTILITIES",
                            "SOFTWARE",
                            "OTHER"
                          ]
                        },
                        {
                          "description": "User permission levels and access control",
                          "name": "user_role",
                          "values": [
                            "ADMIN",
                            "USER",
                            "VIEWER"
                          ]
                        }
                      ],
                      "message": "Database enums retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/DatabaseEnumsResponse"
                }
              }
            },
            "description": "Database enums retrieved successfully"
          },
          "500": {
            "content": {
              "application/json": {
                "examples": {
                  "enums-service-error": {
                    "summary": "Error retrieving enums",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "Failed to retrieve database enums",
                      "statusCode": 500
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error"
          }
        },
        "summary": "Get all database enums",
        "tags": [
          "Database Documentation"
        ]
      }
    },
    "/database-docs/env-variables": {
      "get": {
        "description": "Retrieves documentation for all required and optional environment variables.\n      \n## Environment Categories\n- **Database**: Supabase connection and configuration variables\n- **Authentication**: OAuth and session management settings\n- **Storage**: File upload and storage configuration\n- **External APIs**: Third-party service integration settings\n- **Application**: General application configuration\n\n## Variable Types\n- **Required**: Essential variables for application functionality\n- **Optional**: Variables for optional features or development\n- **Sensitive**: Variables containing secrets or credentials\n- **Public**: Variables safe for client-side exposure\n\n## Configuration Groups\n- **Development**: Variables needed for local development\n- **Production**: Variables required for production deployment\n- **Testing**: Variables for test environment configuration\n- **CI/CD**: Variables for continuous integration and deployment\n\n## Use Cases\n- **Environment Setup**: Complete reference for environment configuration\n- **Deployment**: Required variables for production deployment\n- **Development**: Local development environment setup\n- **Documentation**: Reference for configuration management",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-env-variables": {
                    "summary": "Successful environment variables retrieval",
                    "value": {
                      "data": {
                        "application": {
                          "API_BASE_URL": "Base URL for API endpoints",
                          "FRONTEND_URL": "Frontend application URL for CORS and redirects",
                          "NODE_ENV": "Application environment (development, production, test)",
                          "PORT": "Server port number (default: 3000)"
                        },
                        "authentication": {
                          "GOOGLE_CLIENT_ID": "Google OAuth client ID for authentication",
                          "GOOGLE_CLIENT_SECRET": "Google OAuth client secret for authentication",
                          "JWT_SECRET": "Secret key for JWT token signing and verification",
                          "NEXTAUTH_SECRET": "NextAuth.js secret for session encryption"
                        },
                        "database": {
                          "DATABASE_URL": "Direct PostgreSQL connection URL for migrations",
                          "SUPABASE_ANON_KEY": "Supabase anonymous key for client-side operations",
                          "SUPABASE_SERVICE_ROLE_KEY": "Supabase service role key for server-side operations",
                          "SUPABASE_URL": "Supabase project URL for database connection"
                        },
                        "external": {
                          "OPENAI_API_KEY": "OpenAI API key for AI-powered features",
                          "SENDGRID_API_KEY": "SendGrid API key for email notifications",
                          "STRIPE_SECRET_KEY": "Stripe secret key for payment processing"
                        }
                      },
                      "message": "Environment variables retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/EnvVariablesResponse"
                }
              }
            },
            "description": "Environment variables retrieved successfully"
          },
          "500": {
            "content": {
              "application/json": {
                "examples": {
                  "env-variables-error": {
                    "summary": "Error retrieving environment variables",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "Failed to retrieve environment variables documentation",
                      "statusCode": 500
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error"
          }
        },
        "summary": "Get environment variables documentation",
        "tags": [
          "Database Documentation"
        ]
      }
    },
    "/database-docs/models": {
      "get": {
        "description": "Retrieves all database models with complete field definitions, relations, and metadata.\n      \n## Model Information\n- **Table Structure**: Complete field definitions with types and constraints\n- **Relationships**: Foreign key relationships and cardinality information\n- **Business Context**: Model descriptions and categorization\n- **Index Information**: Database indexes for performance optimization\n\n## Field Details\n- **Data Types**: PostgreSQL/Supabase data types (UUID, String, DateTime, etc.)\n- **Constraints**: Nullable, default values, and validation rules\n- **Descriptions**: Human-readable field descriptions and usage notes\n- **Primary Keys**: Identification of primary key fields\n\n## Relationship Mapping\n- **One-to-One**: Direct relationships between models\n- **One-to-Many**: Parent-child relationships\n- **Many-to-One**: Child-parent relationships\n- **Related Models**: Target model names for foreign key relationships\n\n## Use Cases\n- **Type Generation**: Frontend TypeScript type generation\n- **API Development**: Understanding data structures for endpoints\n- **Database Migration**: Reference for schema changes\n- **Documentation**: Complete model reference for development",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-models-retrieval": {
                    "summary": "Successful database models retrieval",
                    "value": {
                      "data": [
                        {
                          "category": "Core",
                          "description": "User accounts with preferences and authentication data",
                          "displayName": "User Profiles",
                          "fields": [
                            {
                              "description": "Primary key (from Supabase Auth)",
                              "name": "id",
                              "nullable": false,
                              "type": "UUID"
                            },
                            {
                              "description": "Unique email address",
                              "name": "email",
                              "nullable": true,
                              "type": "String"
                            },
                            {
                              "name": "display_name",
                              "nullable": true,
                              "type": "String"
                            },
                            {
                              "name": "created_at",
                              "nullable": true,
                              "type": "DateTime"
                            }
                          ],
                          "name": "user_profiles",
                          "relations": [
                            {
                              "name": "companies",
                              "relatedModel": "companies",
                              "type": "one-to-many"
                            },
                            {
                              "name": "documents",
                              "relatedModel": "documents",
                              "type": "one-to-many"
                            }
                          ]
                        },
                        {
                          "category": "Core",
                          "description": "Multi-tenant company management with owner relationships",
                          "displayName": "Companies",
                          "fields": [
                            {
                              "name": "id",
                              "nullable": false,
                              "type": "UUID"
                            },
                            {
                              "description": "FK to user_profiles",
                              "name": "owner_id",
                              "nullable": false,
                              "type": "UUID"
                            },
                            {
                              "name": "name",
                              "nullable": false,
                              "type": "String"
                            },
                            {
                              "default": "true",
                              "name": "is_active",
                              "nullable": true,
                              "type": "Boolean"
                            }
                          ],
                          "name": "companies",
                          "relations": [
                            {
                              "name": "owner",
                              "relatedModel": "user_profiles",
                              "type": "many-to-one"
                            }
                          ]
                        }
                      ],
                      "message": "Database models retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/DatabaseModelsResponse"
                }
              }
            },
            "description": "Database models retrieved successfully"
          },
          "500": {
            "content": {
              "application/json": {
                "examples": {
                  "models-service-error": {
                    "summary": "Error retrieving models",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "Failed to retrieve database models",
                      "statusCode": 500
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error"
          }
        },
        "summary": "Get all database models",
        "tags": [
          "Database Documentation"
        ]
      }
    },
    "/database-docs/stats": {
      "get": {
        "description": "Retrieves real-time statistics and metrics about the database schema.\n      \n## Statistics Overview\n- **Model Counts**: Total number of database models/tables\n- **Field Counts**: Total fields across all models\n- **Relationship Counts**: Total relationships between models\n- **Enum Counts**: Total number of database enums\n- **Category Distribution**: Models grouped by business categories\n\n## Metrics Details\n- **Schema Complexity**: Indicators of database schema complexity\n- **Relationship Density**: How interconnected the models are\n- **Category Distribution**: Business domain organization\n- **Field Distribution**: Average fields per model\n\n## Real-time Data\n- **Live Counts**: Current counts based on schema registry\n- **Category Analysis**: Dynamic categorization of models\n- **Relationship Mapping**: Current relationship structure\n- **Schema Health**: Indicators of schema organization\n\n## Use Cases\n- **Schema Analysis**: Understanding database structure and complexity\n- **Documentation Metrics**: Statistics for documentation completeness\n- **Development Planning**: Insights for schema evolution\n- **Performance Planning**: Understanding schema size for optimization",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-stats-retrieval": {
                    "summary": "Successful database statistics retrieval",
                    "value": {
                      "data": {
                        "categories": [
                          "Core",
                          "Business",
                          "System",
                          "Audit",
                          "Configuration"
                        ],
                        "totalEnums": 8,
                        "totalFields": 120,
                        "totalModels": 15,
                        "totalRelations": 45
                      },
                      "message": "Database statistics retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/DatabaseStatsResponse"
                }
              }
            },
            "description": "Database statistics retrieved successfully"
          },
          "500": {
            "content": {
              "application/json": {
                "examples": {
                  "stats-service-error": {
                    "summary": "Error retrieving database statistics",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "Failed to retrieve database statistics",
                      "statusCode": 500
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error"
          }
        },
        "summary": "Get database statistics and metrics",
        "tags": [
          "Database Documentation"
        ]
      }
    },
    "/database-docs/supabase": {
      "get": {
        "description": "Retrieves Supabase feature configuration and integration documentation.\n      \n## Supabase Features\n- **Authentication**: User authentication and session management\n- **Row Level Security**: Database-level security policies\n- **Storage**: File upload and management system\n- **Real-time**: WebSocket connections and live data updates\n- **Edge Functions**: Serverless function execution\n- **Database**: PostgreSQL database with extensions\n\n## Configuration Details\n- **Environment Variables**: Required Supabase configuration variables\n- **Feature Descriptions**: Detailed explanation of each Supabase feature\n- **Integration Points**: How features connect with the application\n- **Security Settings**: Authentication and authorization configurations\n\n## Environment Setup\n- **Project URL**: Supabase project endpoint configuration\n- **API Keys**: Anonymous and service role key usage\n- **Database URL**: Direct database connection settings\n- **Storage Buckets**: File storage configuration\n\n## Use Cases\n- **Development Setup**: Environment configuration for new developers\n- **Feature Documentation**: Understanding available Supabase features\n- **Integration Reference**: How to use Supabase features in the application\n- **Security Configuration**: Proper security setup and best practices",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-supabase-config": {
                    "summary": "Successful Supabase configuration retrieval",
                    "value": {
                      "data": [
                        {
                          "description": "User authentication and session management with OAuth providers",
                          "envVar": "SUPABASE_URL",
                          "feature": "Authentication"
                        },
                        {
                          "description": "Database-level security policies for data access control",
                          "envVar": "SUPABASE_ANON_KEY",
                          "feature": "Row Level Security"
                        },
                        {
                          "description": "File upload and management with bucket-based organization",
                          "envVar": "SUPABASE_SERVICE_ROLE_KEY",
                          "feature": "Storage"
                        },
                        {
                          "description": "WebSocket connections for live data updates and notifications",
                          "feature": "Real-time"
                        },
                        {
                          "description": "Serverless function execution for backend logic",
                          "feature": "Edge Functions"
                        }
                      ],
                      "message": "Supabase configuration retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/SupabaseConfigResponse"
                }
              }
            },
            "description": "Supabase configuration retrieved successfully"
          },
          "500": {
            "content": {
              "application/json": {
                "examples": {
                  "supabase-config-error": {
                    "summary": "Error retrieving Supabase configuration",
                    "value": {
                      "error": "Internal Server Error",
                      "message": "Failed to retrieve Supabase configuration",
                      "statusCode": 500
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error"
          }
        },
        "summary": "Get Supabase configuration documentation",
        "tags": [
          "Database Documentation"
        ]
      }
    },
    "/deadlines": {
      "get": {
        "parameters": [
          {
            "in": "query",
            "name": "status",
            "schema": {
              "enum": [
                "upcoming",
                "due_soon",
                "overdue",
                "completed",
                "not_applicable",
                "dismissed",
                "closed"
              ],
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "from",
            "schema": {
              "format": "date",
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "to",
            "schema": {
              "format": "date",
              "type": "string"
            }
          },
          {
            "description": "true also returns rows an earlier 事業年度 pick dated (superseded: true) — the calendar shows them under 履歴・旧表示. Left out by default.",
            "in": "query",
            "name": "include_superseded",
            "schema": {
              "default": false,
              "type": "boolean"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "items": {
                        "$ref": "#/components/schemas/DeadlineObject"
                      },
                      "type": "array"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "List of deadline objects"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List deadline objects for current user",
        "tags": [
          "Deadlines"
        ]
      }
    },
    "/deadlines/next": {
      "get": {
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                }
              }
            },
            "description": "Next 3 upcoming deadlines"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Next 3 upcoming deadlines (KPI card)",
        "tags": [
          "Deadlines"
        ]
      }
    },
    "/deadlines/recompute": {
      "post": {
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "skipped": {
                          "type": "integer"
                        },
                        "upserted": {
                          "type": "integer"
                        }
                      },
                      "type": "object"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Recompute result"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Recompute all deadlines for current user",
        "tags": [
          "Deadlines"
        ]
      }
    },
    "/deadlines/rules": {
      "get": {
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "items": {
                        "$ref": "#/components/schemas/ComplianceRule"
                      },
                      "type": "array"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Active rule versions"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List active compliance rule versions",
        "tags": [
          "Deadlines"
        ]
      }
    },
    "/deadlines/{id}": {
      "get": {
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                }
              }
            },
            "description": "Deadline detail"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get deadline detail with legal basis",
        "tags": [
          "Deadlines"
        ]
      }
    },
    "/deadlines/{id}/complete": {
      "post": {
        "description": "Every body field is optional; a bodiless POST records today (JST). `filedOnUnknown: true` records no date (never today), with `filedMonth` when the owner remembers the month. `trackingNumber` (簡易書留) needs `filingMethod: 'mail'`. `receiptNumber` is a 受付番号 only — letters, digits and hyphens. `evidenceFileId` must be one of the caller’s own uploads. Writes a deadline_audit_events row. Undo with POST /deadlines/{id}/reopen.",
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "additionalProperties": false,
                "properties": {
                  "evidenceFileId": {
                    "format": "uuid",
                    "type": "string"
                  },
                  "filedMonth": {
                    "description": "「○月頃」 (YYYY-MM), only with filedOnUnknown. Not in the future.",
                    "example": "2026-07",
                    "pattern": "^\\d{4}-(0[1-9]|1[0-2])$",
                    "type": "string"
                  },
                  "filedOn": {
                    "description": "Not in the future (JST). Default today.",
                    "format": "date",
                    "type": "string"
                  },
                  "filedOnUnknown": {
                    "description": "「提出日が不明」: no date is stored. Not with filedOn.",
                    "enum": [
                      true
                    ],
                    "type": "boolean"
                  },
                  "filingMethod": {
                    "description": "提出方法: eLTAX / e-Tax / 郵送 / 窓口 / その他",
                    "enum": [
                      "eltax",
                      "etax",
                      "mail",
                      "counter",
                      "other"
                    ],
                    "type": "string"
                  },
                  "kind": {
                    "description": "`filed` (「提出しました」) on a row whose payment the bank does not show paid records the filing and keeps the row open; `paid` or absent completes it. Paid after a filing keeps the filing date.",
                    "enum": [
                      "filed",
                      "paid"
                    ],
                    "type": "string"
                  },
                  "receiptNumber": {
                    "description": "受付番号 (e-Tax / eLTAX). Full-width digits and hyphens are folded first.",
                    "example": "20261015123456789012",
                    "pattern": "^[A-Za-z0-9][A-Za-z0-9-]{3,49}$",
                    "type": "string"
                  },
                  "trackingNumber": {
                    "description": "簡易書留・特定記録の追跡番号, only with filingMethod mail.",
                    "pattern": "^[A-Za-z0-9][A-Za-z0-9-]{3,49}$",
                    "type": "string"
                  }
                },
                "type": "object"
              }
            }
          },
          "required": false
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "completedAt": {
                          "nullable": true,
                          "type": "string"
                        },
                        "filedOn": {
                          "description": "Null when recorded as 「提出日が不明」.",
                          "format": "date",
                          "nullable": true,
                          "type": "string"
                        },
                        "id": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "paymentPending": {
                          "type": "boolean"
                        },
                        "status": {
                          "description": "`completed`, or the row’s open status when it was filed with the payment owed",
                          "type": "string"
                        }
                      },
                      "required": [
                        "id",
                        "status",
                        "filedOn",
                        "completedAt",
                        "paymentPending"
                      ],
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Marked as filed"
          },
          "400": {
            "description": "Invalid body (bad date, future date, unknown field)"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Deadline or evidence file not found, or the deadline is dismissed"
          },
          "409": {
            "description": "Completed automatically from SBC records (engine or 源泉 register), superseded, a row of the election / lock-in register (nothing to file), or changed by another operation while saving"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "「提出しました」 — mark as filed: 提出日 (or 提出日が不明), 提出方法, optional 受付番号 / 追跡番号 / 控え file",
        "tags": [
          "Deadlines"
        ]
      }
    },
    "/deadlines/{id}/dismiss": {
      "post": {
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Dismissed"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Not found, or already completed"
          },
          "409": {
            "description": "Superseded (旧表示), or a row of the election / lock-in register (nothing to file)"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Dismiss a deadline (対象外)",
        "tags": [
          "Deadlines"
        ]
      }
    },
    "/deadlines/{id}/guidance": {
      "get": {
        "description": "Plain-Japanese guidance for a deadline object. `why` is rendered from the facts the engine used; `yourValues` is the owner’s own 4・5・6月 報酬 for 算定基礎届 (null for other rules); `unverified` lists claims no primary source settled (shown as 確認中).",
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/ObligationGuidance"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Guidance"
          },
          "400": {
            "description": "Invalid id"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Not found (or not the caller’s)"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Guidance for one obligation: what / why it applies / how / your values / if missed / sources",
        "tags": [
          "Deadlines"
        ]
      }
    },
    "/deadlines/{id}/interim-comparison": {
      "get": {
        "description": "Prices the first six months of the 事業年度 from the books (税引前利益 + 交際費 over the 6-month limit + 住民税 booked to 租税公課 − 繰越欠損金) at 6-month brackets, and compares it with the 予定 figures the spine stored (or the saved 納付書). Read-only estimate; a filed 仮決算 needs a real six-month close.",
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/InterimComparison"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Comparison"
          },
          "400": {
            "description": "Invalid id, or not a corporate_tax_interim deadline"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Not found (or not the caller’s)"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "中間申告: 予定申告 vs 仮決算 for a corporate_tax_interim deadline",
        "tags": [
          "Deadlines"
        ]
      }
    },
    "/deadlines/{id}/reopen": {
      "post": {
        "description": "Clears the filed record and returns the status the engine settles on (date status, or not_applicable). A 課税期間短縮 quarter the engine completed from tax_return_sessions is refused with 409.",
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "id": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "status": {
                          "enum": [
                            "upcoming",
                            "due_soon",
                            "overdue",
                            "completed",
                            "not_applicable",
                            "dismissed",
                            "closed"
                          ],
                          "type": "string"
                        }
                      },
                      "required": [
                        "id",
                        "status"
                      ],
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Reopened"
          },
          "400": {
            "description": "Invalid id"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Not found"
          },
          "409": {
            "description": "Not completed or dismissed, or completed by the engine"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Undo a completion or a dismissal the owner recorded",
        "tags": [
          "Deadlines"
        ]
      }
    },
    "/demo-processing/run": {
      "post": {
        "description": "Persist a demo processing execution result.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/RunDemoProcessingRequest"
              }
            }
          }
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProcessingRunResponse"
                }
              }
            },
            "description": "Processing run saved"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Save processing run result",
        "tags": [
          "Demo Processing"
        ]
      }
    },
    "/demo-processing/runs": {
      "get": {
        "description": "Get paginated history of processing runs.",
        "parameters": [
          {
            "in": "query",
            "name": "page_size",
            "schema": {
              "default": 20,
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "page_number",
            "schema": {
              "default": 1,
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "company_id",
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "session_id",
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Processing runs list retrieved"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List processing runs",
        "tags": [
          "Demo Processing"
        ]
      }
    },
    "/demo-processing/runs/latest": {
      "get": {
        "parameters": [
          {
            "in": "query",
            "name": "company_id",
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "session_id",
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Latest run retrieved"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get latest processing run",
        "tags": [
          "Demo Processing"
        ]
      }
    },
    "/demo-processing/runs/{runId}": {
      "get": {
        "parameters": [
          {
            "in": "path",
            "name": "runId",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Processing run retrieved"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get processing run by ID",
        "tags": [
          "Demo Processing"
        ]
      }
    },
    "/demo/reset": {
      "post": {
        "description": "Perform comprehensive demo data reset operation with complete cleanup.\n\n## Demo Data Reset Operation\nComprehensive data cleanup with:\n- **Complete Data Removal**: Removes all demo user data across all entities\n- **Cascading Cleanup**: Handles related data and foreign key relationships\n- **Transaction Safety**: Ensures atomic operations with rollback capability\n- **Performance Optimization**: Efficient bulk operations for large datasets\n- **Audit Logging**: Complete audit trail of reset operations\n- **Concurrency Protection**: Prevents concurrent reset operations\n\n## Data Cleanup Scope\n- **Bank Statements**: All demo bank statement records and transactions\n- **Clients**: All demo client records and related data\n- **Journal Entries**: All demo accounting entries and general ledger lines\n- **Documents**: All demo document records and file references\n- **Pay Slips**: All demo payroll records and related items\n- **Sales Invoices**: All demo invoice records and line items\n- **Reconciliation Rules**: All demo reconciliation rules and configurations\n- **Companies**: All demo company records and organizational data\n\n## Security Requirements\n- **Admin Authentication**: Requires valid admin token in x-admin-token header\n- **Environment Configuration**: Demo management must be enabled\n- **Audit Logging**: All operations logged for security monitoring\n- **Access Control**: Restricted to authorized administrators only\n\n## Operation Safety\n- **Concurrency Control**: Prevents multiple simultaneous reset operations\n- **Transaction Management**: Ensures data consistency during cleanup\n- **Error Handling**: Comprehensive error handling with rollback capability\n- **Performance Monitoring**: Tracks operation duration and performance\n- **Validation**: Pre and post-operation validation checks\n\n## Use Cases\n- **Demo Environment Refresh**: Reset demo data for clean testing environment\n- **Performance Testing**: Clear data for performance benchmark testing\n- **Security Testing**: Reset data for security audit and penetration testing\n- **Training Preparation**: Prepare clean demo environment for training sessions\n- **Maintenance Operations**: Regular maintenance and cleanup operations\n\n## Admin Authentication Required\nThis endpoint requires admin authentication via x-admin-token header. The token must match the configured DEMO_ADMIN_TOKEN environment variable.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DemoResetResponse"
                }
              }
            },
            "description": "Demo data reset completed successfully"
          },
          "401": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DemoErrorResponse"
                }
              }
            },
            "description": "Unauthorized - Invalid admin token"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DemoErrorResponse"
                }
              }
            },
            "description": "Forbidden - Demo management not configured"
          },
          "500": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DemoErrorResponse"
                }
              }
            },
            "description": "Demo data reset failed"
          }
        },
        "security": [
          {
            "adminToken": []
          }
        ],
        "summary": "Reset demo data (admin only)",
        "tags": [
          "Demo Data Management"
        ]
      }
    },
    "/demo/status": {
      "get": {
        "description": "Get comprehensive demo mode status, statistics, and validation results.\n\n## Demo Status Information\nProvides complete demo environment status with:\n- **Demo Mode Status**: Whether demo mode is enabled or disabled\n- **Demo User Information**: Demo user ID and configuration details\n- **Reset History**: Last reset timestamp and operation history\n- **Data Statistics**: Complete count of all demo data entities\n- **Data Validation**: Integrity check results and identified issues\n- **Environment Status**: Configuration and operational status\n\n## Data Statistics Coverage\n- **Bank Statements**: Demo bank statement records for transaction testing\n- **Clients**: Demo client records for customer relationship testing\n- **Journal Entries**: Demo accounting entries for financial testing\n- **Documents**: Demo document records for document management testing\n- **Pay Slips**: Demo payroll records for HR system testing\n- **Sales Invoices**: Demo invoice records for billing system testing\n- **Companies**: Demo company records for multi-tenant testing\n\n## Validation Checks\n- **Minimum Data Requirements**: Ensures essential demo data exists\n- **Data Integrity**: Validates relationships and consistency\n- **Configuration Validation**: Checks environment configuration\n- **Operational Status**: Verifies system operational readiness\n\n## Use Cases\n- **System Health Check**: Monitor demo environment health\n- **Data Monitoring**: Track demo data volume and integrity\n- **Troubleshooting**: Identify issues with demo data setup\n- **Performance Monitoring**: Track demo data performance metrics\n- **Integration Testing**: Verify demo data for testing scenarios\n\n## Public Access\nNo authentication required - this endpoint provides public status information for demo environment monitoring.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DemoStatusResponse"
                }
              }
            },
            "description": "Demo status retrieved successfully"
          },
          "500": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DemoErrorResponse"
                }
              }
            },
            "description": "Failed to get demo status"
          }
        },
        "summary": "Get demo mode status and statistics",
        "tags": [
          "Demo Data Management"
        ]
      }
    },
    "/demo/validate": {
      "get": {
        "description": "Perform comprehensive demo data integrity validation and health checks.\n\n## Demo Data Validation\nComprehensive validation system with:\n- **Data Integrity Checks**: Validates data consistency and relationships\n- **Minimum Data Requirements**: Ensures essential demo data exists\n- **Configuration Validation**: Checks environment and system configuration\n- **Relationship Validation**: Verifies foreign key relationships and data consistency\n- **Business Logic Validation**: Ensures data meets business rule requirements\n- **Performance Validation**: Checks for performance-impacting data issues\n\n## Validation Categories\n- **Essential Data Presence**: Verifies minimum required demo data exists\n- **Data Consistency**: Checks for data inconsistencies and corruption\n- **Relationship Integrity**: Validates foreign key relationships\n- **Business Rules**: Ensures data complies with business logic requirements\n- **Configuration Compliance**: Verifies system configuration correctness\n- **Performance Impact**: Identifies potential performance issues\n\n## Validation Checks\n- **Company Data**: Ensures demo company exists and is properly configured\n- **Client Data**: Validates demo client records and relationships\n- **Bank Statement Data**: Checks bank statement data integrity and completeness\n- **Journal Entry Data**: Validates accounting entry consistency and balance\n- **Document Data**: Ensures document records are properly linked and accessible\n- **System Configuration**: Validates environment and system settings\n\n## Validation Results\n- **Overall Status**: Boolean indicator of overall data validity\n- **Issue List**: Detailed list of identified validation issues\n- **Statistics**: Complete data statistics for analysis\n- **Recommendations**: Suggested actions for resolving identified issues\n- **Severity Classification**: Classification of issues by severity level\n\n## Use Cases\n- **Health Monitoring**: Regular health checks of demo environment\n- **Troubleshooting**: Identify and diagnose demo data issues\n- **Quality Assurance**: Ensure demo data quality for testing\n- **Maintenance Planning**: Plan maintenance based on validation results\n- **Performance Optimization**: Identify performance optimization opportunities\n\n## Public Access\nNo authentication required - this endpoint provides public validation information for demo environment monitoring and troubleshooting.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DemoValidationResult"
                }
              }
            },
            "description": "Demo data validation completed successfully"
          },
          "500": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DemoErrorResponse"
                }
              }
            },
            "description": "Demo validation failed"
          }
        },
        "summary": "Validate demo data integrity",
        "tags": [
          "Demo Data Management"
        ]
      }
    },
    "/document-templates": {
      "get": {
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "items": {
                        "$ref": "#/components/schemas/DocumentTemplate"
                      },
                      "type": "array"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "OK"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List the authenticated user's templates",
        "tags": [
          "Document Templates"
        ]
      },
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateDocumentTemplateBody"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "description": "Template created"
          },
          "400": {
            "description": "Validation error"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create a new template",
        "tags": [
          "Document Templates"
        ]
      }
    },
    "/document-templates/extract": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ExtractDocumentTemplateBody"
              }
            },
            "multipart/form-data": {
              "schema": {
                "properties": {
                  "description": {
                    "type": "string"
                  },
                  "file": {
                    "format": "binary",
                    "type": "string"
                  }
                },
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/ExtractedSkeleton"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Extracted skeleton"
          },
          "400": {
            "description": "No file or description provided"
          },
          "422": {
            "description": "Extraction failed"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "AI-extract a field skeleton from file or description",
        "tags": [
          "Document Templates"
        ]
      }
    },
    "/document-templates/{id}": {
      "delete": {
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "204": {
            "description": "Archived"
          },
          "404": {
            "description": "Not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Archive (soft-delete) template",
        "tags": [
          "Document Templates"
        ]
      },
      "get": {
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK"
          },
          "404": {
            "description": "Not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get template by ID",
        "tags": [
          "Document Templates"
        ]
      },
      "put": {
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateDocumentTemplateBody"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Updated"
          },
          "404": {
            "description": "Not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update template",
        "tags": [
          "Document Templates"
        ]
      }
    },
    "/documents": {
      "get": {
        "description": "Retrieve a paginated list of documents with optional filtering by type.\n\n**v4.30 Enhancement**: Now includes computed fields for list views:\n- **totalAmount**: Computed from document content (null if not available)\n- **linkedDocumentCount**: Count of linked documents (receipts, invoices, etc.)\n\n**v5.3 Enhancement**: New optional parameters for expense wizard integration:\n- **include_link_stats=true**: Returns detailed link statistics (linked_receipt_count, linked_receipt_total, linked_invoice_count)\n- **sort_by/sort_order**: Flexible sorting by created_at, updated_at, document_name, or total_amount\n\n## Computed Fields (NEW)\n\n### totalAmount\nExtracted from document content based on document type:\n| Document Type | Amount Source |\n|---------------|---------------|\n| claims | `content.summary.reimbursementAmount` OR `content.summary.totalAmount` |\n| payment | `content.paymentInfo.amount` |\n| salary_slip | `content.totals.netPay` |\n| sales_invoice, quotation, etc. | `content.summary.totalAmount` |\n\nReturns `null` if amount not extractable (distinguishes \"not available\" from \"zero yen\").\n\n### linkedDocumentCount\nCombined count from:\n- `document_relationships` table (generic document links)\n- `expense_claim_receipts` table (expense claim specific links)\n\nReturns `0` if no links exist.\n\n## Query Parameters\n- **type**: Filter documents by specific document type\n- **page_number**: Page number for pagination (default: 1)\n- **page_size**: Number of documents per page (default: 20, min: 1)\n\n## Document Types\nSupported document types include:\n\n### AI-Generated Documents (with templates):\n- **sales_quotation**: 見積書 - Sales quotations and estimates\n- **sales_invoice**: 請求書 - Sales invoices (インボイス制度 compliant)\n- **service_agreement**: 業務委託契約書 - Service contracts\n- **travel**: 出張報告書 - Travel reports with itinerary\n- **claims**: 立替経費精算書 - Expense reimbursement claims\n- **fixed_asset**: 固定資産台帳 - Fixed asset register\n- **payment**: 支払依頼書 - Payment requests\n- **salary_slip**: 給与明細書 - Payroll and salary documents\n- **company_info**: 定款 - Articles of incorporation\n- **company_decision**: 決定書 - Company decisions/resolutions\n- **company_representative**: 代表者関連書類 - Representative documents\n- **company_capital**: 払込証明書 - Capital payment certificates\n- **company_office_location**: 事業所所在地 - Office location documents\n- **rules_claims**: 旅費規程 - Travel/expense rules\n\n### Tax Documents (generated from accounting data):\n- **tax_journal**: 仕訳帳 - Tax journal entries\n- **tax_general_ledger**: 総勘定元帳 - General ledger\n- **tax_trial_balance**: 試算表 - Trial balance\n- **tax_financial_statements**: 財務諸表 - Financial statements\n- **tax_balance_sheet**: 貸借対照表 - Balance sheet\n- **tax_profit_loss_statement**: 損益計算書 - P&L statement\n- **tax_cash_flow_statement**: キャッシュフロー計算書 - Cash flow\n- **tax_shareholders_equity**: 株主資本等変動計算書 - Equity statement\n- **tax_notes_financial_statements**: 注記表 - Financial notes\n- **tax_corporate**: 法人税 - Corporate tax\n- **tax_local**: 地方税 - Local tax\n- **tax_account_breakdown**: 勘定科目内訳書 - Account breakdown\n- **tax_application_details**: 適用額明細書 - Application details\n- **tax_business_overview**: 事業概況書 - Business overview\n\n## Pagination\nResults are paginated with metadata including:\n- Total count of matching documents\n- Current page and page size\n- Total pages and navigation flags\n- Boolean indicators for next/previous pages\n\n## Security\nOnly returns documents belonging to the authenticated user.\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Filter by document type (single value only, not comma-separated)",
            "in": "query",
            "name": "type",
            "required": false,
            "schema": {
              "enum": [
                "sales_quotation",
                "purchase_order",
                "delivery_note",
                "sales_invoice",
                "service_agreement",
                "travel",
                "claims",
                "fixed_asset",
                "payment",
                "salary_slip",
                "tax_journal",
                "tax_general_ledger",
                "tax_trial_balance",
                "tax_financial_statements",
                "tax_balance_sheet",
                "tax_profit_loss_statement",
                "tax_cash_flow_statement",
                "tax_shareholders_equity",
                "tax_notes_financial_statements",
                "tax_corporate",
                "tax_local",
                "tax_account_breakdown",
                "tax_application_details",
                "tax_business_overview",
                "company_info",
                "company_decision",
                "company_representative",
                "company_capital",
                "company_office_location",
                "rules_claims"
              ],
              "type": "string"
            }
          },
          {
            "description": "Filter by document status (draft or published only)",
            "in": "query",
            "name": "status",
            "required": false,
            "schema": {
              "enum": [
                "draft",
                "published"
              ],
              "type": "string"
            }
          },
          {
            "description": "Page number for pagination",
            "in": "query",
            "name": "page_number",
            "required": false,
            "schema": {
              "default": 1,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "description": "Number of documents per page",
            "in": "query",
            "name": "page_size",
            "required": false,
            "schema": {
              "default": 20,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "description": "Include soft-deleted documents in the results (J-GAAP compliance feature)",
            "in": "query",
            "name": "include_deleted",
            "required": false,
            "schema": {
              "default": false,
              "type": "boolean"
            }
          },
          {
            "description": "Filter by trading partner (client) ID",
            "in": "query",
            "name": "client_id",
            "required": false,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Field to sort by",
            "in": "query",
            "name": "sort_by",
            "required": false,
            "schema": {
              "default": "created_at",
              "enum": [
                "created_at",
                "updated_at",
                "document_name",
                "total_amount"
              ],
              "type": "string"
            }
          },
          {
            "description": "Sort order (ascending or descending)",
            "in": "query",
            "name": "sort_order",
            "required": false,
            "schema": {
              "default": "desc",
              "enum": [
                "asc",
                "desc"
              ],
              "type": "string"
            }
          },
          {
            "description": "Include journal entry status inline (v4.29+). Adds has_journal_entry, journal_entry_id, journal_status, total_debit, total_credit fields.",
            "in": "query",
            "name": "include_journal_status",
            "required": false,
            "schema": {
              "default": false,
              "type": "boolean"
            }
          },
          {
            "description": "Include link statistics inline (v5.3+). Adds linked_receipt_count, linked_receipt_total, linked_invoice_count fields. Useful for expense wizard showing which claims have receipts attached.",
            "in": "query",
            "name": "include_link_stats",
            "required": false,
            "schema": {
              "default": false,
              "type": "boolean"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DocumentListResponse"
                }
              }
            },
            "description": "Documents retrieved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List documents with computed fields (v5.3 Enhanced)",
        "tags": [
          "Documents"
        ]
      }
    },
    "/documents/auto-save": {
      "get": {
        "description": "Retrieve an auto-saved draft document for the specified type.\n\n## Query Parameters\n- **document_id**: Optional specific document ID to check for auto-save\n- **type**: Document type to find auto-save for (required)\n\n## Auto-Save Functionality\nThe system automatically saves:\n- Draft documents during editing\n- Unsaved changes periodically\n- Form data before navigation\n- Content during long editing sessions\n\n## Response Behavior\n- Returns the auto-save document if one exists\n- Returns null if no auto-save document is found\n- Prioritizes specific document ID if provided\n- Falls back to type-based search\n\n## Use Cases\n- Recovering unsaved work\n- Continuing interrupted editing sessions\n- Preventing data loss\n- Seamless user experience\n\n## Security\nOnly returns auto-save documents belonging to the authenticated user.\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Optional specific document ID to check",
            "in": "query",
            "name": "document_id",
            "required": false,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Document type to find auto-save for",
            "in": "query",
            "name": "type",
            "required": true,
            "schema": {
              "enum": [
                "sales_quotation",
                "purchase_order",
                "delivery_note",
                "sales_invoice",
                "service_agreement",
                "travel",
                "claims",
                "fixed_asset",
                "payment",
                "salary_slip",
                "tax_journal",
                "tax_general_ledger",
                "tax_trial_balance",
                "tax_financial_statements",
                "tax_balance_sheet",
                "tax_profit_loss_statement",
                "tax_cash_flow_statement",
                "tax_shareholders_equity",
                "tax_notes_financial_statements",
                "tax_corporate",
                "tax_local",
                "tax_account_breakdown",
                "tax_application_details",
                "tax_business_overview",
                "company_info",
                "company_decision",
                "company_representative",
                "company_capital",
                "company_office_location",
                "rules_claims"
              ],
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AutoSaveDocumentResponse"
                }
              }
            },
            "description": "Auto-save document retrieved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get auto-save document",
        "tags": [
          "Documents"
        ]
      }
    },
    "/documents/batch": {
      "get": {
        "description": "Retrieve documents for multiple types in a single request for improved performance.\n\n## Query Parameters\n- **types**: Comma-separated list of document types to retrieve\n- **page_size**: Number of documents per type (default: 100)\n- **include_attachment_count**: Include attachment counts (default: false)\n\n## Response Fields (v4.45)\nEach document includes SQL-computed fields:\n- **linked_document_count**: Bidirectional count from `document_relationships` + `expense_claim_receipts`\n- **total_amount**: Extracted from document content based on type\n- **payment_type**: For salary_slip/payment documents (v4.43)\n- **payment_type_label**: Japanese label for payment type (v4.43)\n\n## v4.45 Stale Data Fix\nThe `linked_document_count` is now computed directly in the SQL query with bidirectional relationship counting (parent AND child). This ensures accurate counts for all document types.\n\n## Batch Processing\nThis endpoint:\n- Processes multiple document types in parallel\n- Returns results grouped by document type\n- Includes pagination metadata for each type\n- Optimizes API calls for dashboard loading\n\n## Cache-Control\nResponse includes `no-store, no-cache` headers to ensure real-time data.\n\n## Error Handling\n- Continues processing even if some types fail\n- Returns partial results with error logging\n- Individual type failures don't affect others\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Comma-separated list of document types",
            "example": "sales_invoice,sales_quotation,service_agreement",
            "in": "query",
            "name": "types",
            "required": true,
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "Number of documents per type",
            "in": "query",
            "name": "page_size",
            "required": false,
            "schema": {
              "default": 100,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "description": "Include attachment counts in response (v4.45). Note: linked_document_count is always included from SQL.",
            "in": "query",
            "name": "include_attachment_count",
            "required": false,
            "schema": {
              "default": false,
              "type": "boolean"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DocumentBatchResponse"
                }
              }
            },
            "description": "Documents batch retrieved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get documents batch by types (v4.45)",
        "tags": [
          "Documents"
        ]
      }
    },
    "/documents/batch-linked-documents": {
      "get": {
        "description": "\n**v4.47: N+1 Query Problem Solution (Industry Standard Implementation)**\n\nGet full linked document details for multiple documents in ONE request.\nThis endpoint solves the N+1 query problem in document list views.\n\n**Industry Standard Pattern:**\nBased on Facebook Graph API and Google Workspace batch patterns:\n- Per-item status codes (200=success, 404=not found)\n- Partial success support (failed items don't fail entire batch)\n- Request metadata for debugging (batchId, processingTimeMs)\n\n**Before (N+1 problem):**\n- Fetch document list (1 request)\n- For each document, fetch linked docs (N requests)\n- Total: 1 + N requests\n\n**After (batch endpoint):**\n- Fetch document list (1 request)\n- Fetch all linked docs in batch (1 request)\n- Total: 2 requests\n\n**Response Structure:**\n```json\n{\n  \"results\": {\n    \"doc-id-1\": {\n      \"code\": 200,\n      \"data\": { \"documentId\": \"...\", \"linkedDocuments\": [...] }\n    },\n    \"doc-id-2\": {\n      \"code\": 404,\n      \"error\": \"Document not found or access denied\"\n    }\n  },\n  \"totalDocuments\": 100,\n  \"processedCount\": 98,\n  \"failedCount\": 2,\n  \"_meta\": { \"processingTimeMs\": 150, \"batchId\": \"batch-xxx\" }\n}\n```\n\n**When to use GET vs POST:**\n- **GET**: When batch is small (<50 IDs, ~1800 chars)\n- **POST**: When batch is large (50-100 IDs) to avoid URL length limits\n      ",
        "operationId": "getBatchLinkedDocuments",
        "parameters": [
          {
            "description": "Comma-separated list of document UUIDs (max 100)",
            "in": "query",
            "name": "ids",
            "required": true,
            "schema": {
              "example": "uuid-1,uuid-2,uuid-3",
              "type": "string"
            }
          },
          {
            "description": "Optional filter by relationship type",
            "in": "query",
            "name": "relationship_type",
            "required": false,
            "schema": {
              "enum": [
                "receipt_attachment",
                "invoice_attachment",
                "supporting_document",
                "related_document",
                "source_document",
                "generated_from",
                "payment_to_salary",
                "salary_to_payment"
              ],
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "example": {
                  "data": {
                    "_meta": {
                      "batchId": "batch-1706000000-abc123",
                      "processingTimeMs": 85
                    },
                    "failedCount": 1,
                    "processedCount": 1,
                    "results": {
                      "uuid-1": {
                        "code": 200,
                        "data": {
                          "documentId": "uuid-1",
                          "documentName": "2024年3月出張報告書",
                          "documentType": "travel",
                          "linkedDocumentCount": 1,
                          "linkedDocuments": [
                            {
                              "allocatedAmount": 14000,
                              "amount": 14000,
                              "documentType": "payment",
                              "id": "linked-uuid-1",
                              "linkId": "link-uuid-1",
                              "linkedAt": "2024-03-20T10:00:00Z",
                              "name": "新幹線切符",
                              "relationshipType": "receipt_attachment",
                              "vendorName": "JR東日本"
                            }
                          ],
                          "linkedInvoices": [],
                          "linkedReceipts": [],
                          "totalAllocatedAmount": 14000
                        }
                      },
                      "uuid-2": {
                        "code": 404,
                        "error": "Document not found or access denied"
                      }
                    },
                    "totalDocuments": 2
                  },
                  "message": "Batch linked documents retrieved for 2 documents",
                  "success": true
                },
                "schema": {
                  "$ref": "#/components/schemas/BatchLinkedDocumentsResponse"
                }
              }
            },
            "description": "Batch linked documents retrieved successfully"
          },
          "400": {
            "description": "Invalid request - batch size exceeds limit or invalid UUID format"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get batch linked documents (N+1 optimization)",
        "tags": [
          "Document Linking"
        ]
      },
      "post": {
        "description": "\n**POST Alternative for Large Batches**\n\nSame as GET but accepts JSON body instead of query string.\nUse this when batch exceeds URL length limits (~2000 chars).\n\n**When to use:**\n- GET is limited by URL length (~2000 chars)\n- 100 UUIDs (36 chars each + commas) = ~3700 chars\n- Use POST when batch size > 50 documents\n      ",
        "operationId": "postBatchLinkedDocuments",
        "requestBody": {
          "content": {
            "application/json": {
              "example": {
                "ids": [
                  "uuid-1",
                  "uuid-2",
                  "uuid-3"
                ],
                "relationship_type": "receipt_attachment"
              },
              "schema": {
                "properties": {
                  "ids": {
                    "description": "Array of document UUIDs",
                    "items": {
                      "format": "uuid",
                      "type": "string"
                    },
                    "maxItems": 100,
                    "minItems": 1,
                    "type": "array"
                  },
                  "relationship_type": {
                    "description": "Optional filter by relationship type",
                    "enum": [
                      "receipt_attachment",
                      "invoice_attachment",
                      "supporting_document"
                    ],
                    "type": "string"
                  }
                },
                "required": [
                  "ids"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BatchLinkedDocumentsResponse"
                }
              }
            },
            "description": "Batch linked documents retrieved successfully"
          },
          "400": {
            "description": "Invalid request body"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Batch linked documents (POST for large batches)",
        "tags": [
          "Document Linking"
        ]
      }
    },
    "/documents/bulk": {
      "delete": {
        "description": "Soft delete multiple documents in a single operation.\n\n## J-GAAP Compliance\n- All documents are soft deleted (preserved for audit)\n- Published + locked documents will cause error\n- Use bulk void for accounting documents\n\n## Request Body\n- **documentIds**: Array of document UUIDs to delete\n\n## Response\nReturns count of documents successfully deleted.\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/BulkDeleteDocumentsRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "deletedCount": {
                          "example": 3,
                          "type": "integer"
                        },
                        "success": {
                          "example": true,
                          "type": "boolean"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "3 documents deleted successfully",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Bulk delete operation completed"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "2 documents cannot be deleted because they are published and locked. Use void instead.",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Some documents cannot be deleted"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Bulk soft delete multiple documents",
        "tags": [
          "Documents"
        ]
      }
    },
    "/documents/bulk/lock": {
      "patch": {
        "description": "Lock or unlock multiple documents in a single operation.\n\n## Bulk Operation\n- Processes all provided document IDs\n- Skips deleted and voided documents\n- Returns count of actually updated documents\n\n## Use Cases\n- Locking multiple finalized documents\n- Unlocking batch for corrections\n- Admin operations\n\n## Request Body\n- **documentIds**: Array of document UUIDs\n- **isLocked**: Boolean - set to true to lock, false to unlock\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/BulkLockDocumentsRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BulkOperationResponse"
                }
              }
            },
            "description": "Bulk lock operation completed"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Bulk lock or unlock multiple documents",
        "tags": [
          "Documents"
        ]
      }
    },
    "/documents/by-ids": {
      "get": {
        "description": "Returns up to 50 documents in the same shape as `GET /documents/{document_id}` (`data.document`),\nso a viewer that shows several linked documents makes one request instead of one per document.\n\n## Query Parameters\n- **ids**: comma-separated document UUIDs (1–50 after removing duplicates)\n\n## Response\n- **documents**: the caller's live documents, in request order, each with the same relations and\n  metadata enrichment (`journalEntry`, `expenseAttachmentsResolved`) as the single-document read\n- **missingIds**: requested ids that are unknown, deleted or owned by another user — never an error\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Comma-separated document UUIDs (1–50 distinct)",
            "example": "123e4567-e89b-12d3-a456-426614174000,550e8400-e29b-41d4-a716-446655440000",
            "in": "query",
            "name": "ids",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "documents": {
                          "items": {
                            "additionalProperties": true,
                            "description": "Exactly `data.document` of GET /documents/{document_id}: the documents row with its client, salesInvoice, paySlips and fixedAssets relations. Keys are camelCase on the wire (the response case conversion runs on every API response).",
                            "properties": {
                              "documentName": {
                                "type": "string"
                              },
                              "documentType": {
                                "type": "string"
                              },
                              "id": {
                                "format": "uuid",
                                "type": "string"
                              },
                              "metadata": {
                                "additionalProperties": true,
                                "nullable": true,
                                "type": "object"
                              },
                              "status": {
                                "type": "string"
                              },
                              "userId": {
                                "format": "uuid",
                                "type": "string"
                              }
                            },
                            "required": [
                              "id",
                              "userId",
                              "documentType",
                              "documentName",
                              "status"
                            ],
                            "type": "object"
                          },
                          "type": "array"
                        },
                        "missingIds": {
                          "items": {
                            "format": "uuid",
                            "type": "string"
                          },
                          "type": "array"
                        }
                      },
                      "required": [
                        "documents",
                        "missingIds"
                      ],
                      "type": "object"
                    },
                    "message": {
                      "example": "Documents retrieved successfully",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Documents retrieved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get several documents by ID in one request",
        "tags": [
          "Documents"
        ]
      }
    },
    "/documents/draft": {
      "post": {
        "description": "Create a new draft document with the specified name and type.\n   \n## Request Body\n- **document_name**: Name for the new document (required)\n- **type**: Document type classification (required)\n\n## Draft Document Creation\nCreates a new document with:\n- Status set to 'draft'\n- Empty or default content structure\n- Version number 1\n- Unlocked for editing\n- User ownership established\n\n## Document Workflow\nThe typical document lifecycle:\n1. **Draft**: Created and editable\n2. **Published**: Confirmed and locked\n3. **Archived**: Inactive but preserved\n\n## Use Cases\n- Starting new document creation\n- Template-based document generation\n- Workflow initiation\n- Content management setup\n\n## Security\nDocument is automatically associated with the authenticated user.\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateDocumentRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DocumentCreateResponse"
                }
              }
            },
            "description": "Draft document created successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create a draft document",
        "tags": [
          "Documents"
        ]
      }
    },
    "/documents/generate": {
      "post": {
        "description": "Generate JSON content for a document based on user description and company context using specialized AI prompts.\n\n> 💡 **Tip**: For better UX with real-time progress updates, use the SSE streaming endpoint: `POST /documents/generate/stream`\n\n## Request Body\n- **description**: Natural language description of the document content (required)\n- **type**: Document type to generate (required, must be AI-enabled type)\n\n## AI Generation Process\n1. Fetches user's company information from their profile\n2. Loads the document-specific template with customFields support\n3. Applies specialized prompt engineering for the document type\n4. Uses AI to fill the template intelligently based on description\n5. Returns properly structured JSON matching frontend expectations\n\n## AI-Enabled Document Types (14 types with templates)\n| Type | Japanese Name | Key Features |\n|------|--------------|--------------|\n| sales_quotation | 見積書 | Line items, tax breakdown, terms |\n| sales_invoice | 請求書 | インボイス制度 compliant, registration number |\n| service_agreement | 業務委託契約書 | Rich text clauses, bilingual support |\n| travel | 出張報告書 | Itinerary, outcomes, expense tracking |\n| claims | 立替経費精算書 | Expense categories, tax handling |\n| fixed_asset | 固定資産台帳 | Depreciation methods, asset categories |\n| payment | 支払依頼書 | Payment items, bank info, approvals |\n| salary_slip | 給与明細書 | Japanese payroll standards, deductions |\n| company_info | 定款 | Chapter/article structure |\n| company_decision | 決定書 | Decision items, formal conclusion |\n| company_representative | 代表者関連書類 | Formal correspondence |\n| company_capital | 払込証明書 | Capital amount format |\n| company_office_location | 事業所所在地 | Map coordinates, access info |\n| rules_claims | 旅費規程 | Allowance categories, policies |\n\n## NOT AI-Enabled (generated from accounting data)\nTax documents (tax_journal, tax_general_ledger, etc.) are computed from journal entries, not AI-generated.\n\n## Template Flexibility\nAll templates support:\n- **customFields[]**: Company-specific fields at various levels\n- **customSections[]**: Entirely new document sections\n- **customCategories[]**: Extensible category lists\n- **Array extension**: AI extends arrays based on description\n\n## Japanese Business Standards\n- Proper keigo (敬語) for formal documents\n- Standard Japanese terminology per document type\n- インボイス制度 compliance for invoices\n- Japanese payroll calculation standards\n\n## Example Descriptions\n- 給与明細: \"12月分の給与明細を作成。基本給30万円、残業手当5万円、交通費2万円。\"\n- 見積書: \"Webサイト開発の見積書。デザイン50万円、開発100万円、テスト30万円。\"\n- 出張報告書: \"大阪への2泊3日出張。顧客訪問3件、商談成立2件。\"\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/GenerateDocumentRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DocumentGenerateResponse"
                }
              }
            },
            "description": "Document content generated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Generate document content with AI (Synchronous)",
        "tags": [
          "Documents"
        ]
      }
    },
    "/documents/generate/stream": {
      "post": {
        "description": "**Real-time streaming document generation using Server-Sent Events (SSE).**\n\n## 🎯 Industry Best Practice Implementation\nThis endpoint follows the **OpenAI production best practices** for long-running AI operations:\n- Server-Sent Events (SSE) for real-time updates\n- Heartbeat every 15 seconds for proxy keep-alive\n- Semantic events following OpenAI's pattern\n- Auto-reconnection support via Last-Event-ID\n\n## 📡 SSE Event Types (OpenAI Pattern)\n\n| Event Type | Description | When |\n|------------|-------------|------|\n| `response.created` | Job acknowledged | Immediately |\n| `response.progress` | Progress update (0-100%) | During processing |\n| `response.output_text.delta` | Token-level text | If streaming text |\n| `response.completed` | Full result | On success |\n| `response.failed` | Error details | On failure |\n| `heartbeat` | Keep-alive | Every 15 seconds |\n\n## 🔧 HTTP Headers (Proxy Compatible)\n\n```\nContent-Type: text/event-stream\nCache-Control: no-cache, no-transform\nX-Accel-Buffering: no          # Nginx compatibility\nTransfer-Encoding: identity    # Prevent chunking issues\n```\n\n## 📊 SSE Event Format\n\nEach event follows the standard SSE format:\n```\nid: ai_stream_abc123_1\nevent: response.progress\ndata: {\"id\":\"ai_stream_abc123_1\",\"type\":\"response.progress\",\"timestamp\":\"2026-01-09T10:30:00Z\",\"data\":{\"progress\":40,\"message\":\"Generating document structure...\"}}\n\n```\n\n## 💻 Frontend Integration (JavaScript/TypeScript)\n\n```typescript\nconst response = await fetch('/api/documents/generate/stream', {\n  method: 'POST',\n  headers: {\n    'Content-Type': 'application/json',\n    'Authorization': 'Bearer YOUR_TOKEN'\n  },\n  body: JSON.stringify({ type: 'salary_slip', description: '...' })\n});\n\nconst reader = response.body.getReader();\nconst decoder = new TextDecoder();\n\nwhile (true) {\n  const { done, value } = await reader.read();\n  if (done) break;\n\n  const lines = decoder.decode(value).split('\\n');\n  for (const line of lines) {\n    if (line.startsWith('data: ')) {\n      const event = JSON.parse(line.slice(6));\n      \n      switch (event.type) {\n        case 'response.progress':\n          console.log(`Progress: ${event.data.progress}%`);\n          break;\n        case 'response.completed':\n          console.log('Result:', event.data.result);\n          break;\n        case 'response.failed':\n          console.error('Error:', event.data.error);\n          break;\n      }\n    }\n  }\n}\n```\n\n## 🔄 React Hook Example\n\n```typescript\nconst useStreamingGeneration = () => {\n  const [progress, setProgress] = useState(0);\n  const [message, setMessage] = useState('');\n  const [result, setResult] = useState(null);\n  const [error, setError] = useState(null);\n\n  const generate = async (type: string, description: string) => {\n    // ... SSE handling as shown above\n  };\n\n  return { progress, message, result, error, generate };\n};\n```\n\n## ⚡ Benefits Over Synchronous Endpoint\n\n| Aspect | Sync (/generate) | SSE (/generate/stream) |\n|--------|------------------|------------------------|\n| User Feedback | None until done | Real-time progress |\n| Connection Timeout | Possible on slow AI | Prevented by heartbeat |\n| Perceived Speed | Slow | Fast (immediate feedback) |\n| Proxy Compatible | No | Yes (X-Accel-Buffering) |\n\n## 📚 References\n- [OpenAI Streaming Responses](https://platform.openai.com/docs/guides/streaming-responses)\n- [OpenAI Production Best Practices](https://platform.openai.com/docs/guides/production-best-practices)\n- [SSE for LLMs 2025](https://procedure.tech/blogs/the-streaming-backbone-of-llms-why-server-sent-events-(sse)-still-wins-in-2025)",
        "requestBody": {
          "content": {
            "application/json": {
              "example": {
                "description": "12月分の給与明細を作成。基本給30万円、残業手当5万円、交通費2万円。",
                "type": "salary_slip"
              },
              "schema": {
                "$ref": "#/components/schemas/GenerateDocumentRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "text/event-stream": {
                "schema": {
                  "description": "SSE event stream with semantic events",
                  "example": "id: ai_stream_abc123_1\nevent: response.created\ndata: {\"id\":\"ai_stream_abc123_1\",\"type\":\"response.created\",\"timestamp\":\"2026-01-09T10:30:00Z\",\"data\":{\"jobId\":\"abc123\",\"operationType\":\"document_generation\"}}\n\nid: ai_stream_abc123_2\nevent: response.progress\ndata: {\"id\":\"ai_stream_abc123_2\",\"type\":\"response.progress\",\"timestamp\":\"2026-01-09T10:30:01Z\",\"data\":{\"progress\":40,\"message\":\"Generating document structure...\"}}\n\nid: ai_stream_abc123_3\nevent: response.completed\ndata: {\"id\":\"ai_stream_abc123_3\",\"type\":\"response.completed\",\"timestamp\":\"2026-01-09T10:30:05Z\",\"data\":{\"success\":true,\"result\":{\"documentType\":\"salary_slip\",\"content\":{...}},\"completedAt\":\"2026-01-09T10:30:05Z\"}}",
                  "type": "string"
                }
              }
            },
            "description": "SSE stream established - events will be sent as text/event-stream"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "🔴 SSE: Stream AI document generation (Industry Best Practice 2025)",
        "tags": [
          "Documents"
        ]
      }
    },
    "/documents/has-company-info-document": {
      "get": {
        "description": "Check whether the authenticated user has a published company information document.\n\n## Company Info Document\nThe company info document contains:\n- Company registration details\n- Business information and addresses\n- Contact information\n- Legal and tax identifiers\n- Banking and payment details\n\n## Document Status\nOnly checks for published company info documents:\n- Draft documents are not counted\n- Archived documents are not counted\n- Only published status is considered valid\n\n## Use Cases\n- Onboarding flow validation\n- Feature availability checks\n- Compliance verification\n- Setup completion tracking\n\n## Response\nReturns a boolean indicating whether a valid company info document exists.\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CompanyInfoCheckResponse"
                }
              }
            },
            "description": "Company info document check completed"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Check if user has company info document",
        "tags": [
          "Documents"
        ]
      }
    },
    "/documents/linked-counts": {
      "get": {
        "description": "\nGet linked document counts for multiple documents in a single request.\nUseful for displaying invoice/receipt counts in list views.\n\n**Response includes per document:**\n- Invoice count\n- Receipt count\n- Other document count\n- Total linked count\n      ",
        "operationId": "getDocumentLinkedCounts",
        "parameters": [
          {
            "description": "Comma-separated list of document UUIDs",
            "in": "query",
            "name": "ids",
            "required": true,
            "schema": {
              "example": "uuid-1,uuid-2,uuid-3",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "example": {
                  "data": {
                    "counts": {
                      "uuid-1": {
                        "invoiceCount": 2,
                        "otherCount": 0,
                        "receiptCount": 5,
                        "totalCount": 7
                      },
                      "uuid-2": {
                        "invoiceCount": 0,
                        "otherCount": 1,
                        "receiptCount": 3,
                        "totalCount": 4
                      }
                    }
                  },
                  "message": "Linked document counts retrieved successfully",
                  "success": true
                },
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "counts": {
                          "additionalProperties": {
                            "properties": {
                              "invoiceCount": {
                                "example": 2,
                                "type": "integer"
                              },
                              "otherCount": {
                                "example": 1,
                                "type": "integer"
                              },
                              "receiptCount": {
                                "example": 5,
                                "type": "integer"
                              },
                              "totalCount": {
                                "example": 8,
                                "type": "integer"
                              }
                            },
                            "type": "object"
                          },
                          "type": "object"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Linked document counts retrieved successfully"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get linked document counts (batch)",
        "tags": [
          "Document Linking"
        ]
      }
    },
    "/documents/statistics": {
      "get": {
        "description": "Retrieve comprehensive statistics about user's documents.\n\n## Statistics Included\n- **Total Documents**: Overall count of all documents\n- **By Type**: Document count grouped by document type\n- **By Status**: Document count grouped by status (draft, published, archived)\n- **Recent Activity**: Documents modified in the last 30 days\n\n## Use Cases\n- Dashboard analytics and metrics\n- Document management insights\n- Usage reporting and analysis\n- Performance monitoring\n\n## Data Aggregation\nStatistics are calculated in real-time and include:\n- All document types and statuses\n- Historical activity tracking\n- User-specific metrics only\n- Cached results for performance\n\n## Security\nOnly includes statistics for documents belonging to the authenticated user.\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DocumentStatisticsResponse"
                }
              }
            },
            "description": "Document statistics retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get document statistics",
        "tags": [
          "Documents"
        ]
      }
    },
    "/documents/supported-generation-types": {
      "get": {
        "description": "Retrieve a list of document types that support AI generation with specialized templates and prompts.\n      \n## Response Data\nReturns an array of supported types (14 total), each containing:\n- **type**: The DocumentType enum value (e.g., 'salary_slip')\n- **name**: The Japanese display name (e.g., '給与明細書')\n\n## Supported Document Types\n| type | name | Description |\n|------|------|-------------|\n| claims | 立替経費精算書 | Expense reimbursement claims |\n| travel | 出張報告書 | Travel reports with itinerary |\n| payment | 支払依頼書 | Payment requests |\n| sales_quotation | 見積書 | Sales quotations |\n| sales_invoice | 請求書 | Sales invoices (インボイス制度) |\n| service_agreement | 業務委託契約書 | Service contracts |\n| fixed_asset | 固定資産台帳 | Fixed asset register |\n| company_decision | 決定書 | Company decisions |\n| company_representative | 代表者関連書類 | Representative documents |\n| company_capital | 払込証明書 | Capital certificates |\n| company_office_location | 事業所所在地 | Office location |\n| company_info | 定款 | Articles of incorporation |\n| rules_claims | 旅費規程 | Travel/expense rules |\n| salary_slip | 給与明細書 | Salary slips |\n\n## NOT Included (Tax Documents)\nTax documents (tax_journal, tax_general_ledger, etc.) are NOT included as they are generated from accounting data, not AI.\n\n## Template Features\nEach supported type has:\n- Specialized AI prompt with Japanese business standards\n- Flexible template with customFields support\n- Document-specific validation and calculations\n- Proper Japanese terminology and formatting\n\n## Use Cases\n- Populating dropdowns for \"Generate with AI\" features\n- Validating supported types before generation\n- Discovering available templates and capabilities\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SupportedGenerationTypesResponse"
                }
              }
            },
            "description": "Supported generation types retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get supported AI generation types",
        "tags": [
          "Documents"
        ]
      }
    },
    "/documents/upload-and-link": {
      "post": {
        "description": "\nUpload a file, create a new document, and immediately link it to a source document.\n\n**Flow:**\n1. File is uploaded and processed (OCR, AI analysis)\n2. New document is created with extracted content\n3. New document is linked to the specified source document\n\n**Use case:** User wants to add a new receipt to a travel report.\n      ",
        "operationId": "uploadAndLinkDocument",
        "requestBody": {
          "content": {
            "multipart/form-data": {
              "schema": {
                "properties": {
                  "allocatedAmount": {
                    "description": "Amount to allocate from this document",
                    "type": "number"
                  },
                  "documentType": {
                    "description": "Type of document being uploaded",
                    "enum": [
                      "receipt",
                      "invoice",
                      "expense_receipt",
                      "travel_receipt"
                    ],
                    "type": "string"
                  },
                  "file": {
                    "description": "File to upload: JPEG / PNG / PDF / DOCX, or an e-Gov XML / CSV (UTF-8 or Shift_JIS) as download-only evidence that is never OCR-analyzed. An XML with a DOCTYPE or ENTITY declaration is refused.",
                    "format": "binary",
                    "type": "string"
                  },
                  "linkToDocumentId": {
                    "description": "Document UUID to link the uploaded file to (camelCase)",
                    "format": "uuid",
                    "type": "string"
                  },
                  "note": {
                    "description": "Optional note",
                    "maxLength": 500,
                    "type": "string"
                  },
                  "relationshipType": {
                    "default": "receipt_attachment",
                    "description": "Type of relationship",
                    "enum": [
                      "receipt_attachment",
                      "invoice_attachment",
                      "supporting_document",
                      "related_document"
                    ],
                    "type": "string"
                  }
                },
                "required": [
                  "file",
                  "linkToDocumentId",
                  "documentType"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "documentId": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "documentName": {
                          "type": "string"
                        },
                        "linkId": {
                          "format": "uuid",
                          "type": "string"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "File uploaded and linked successfully",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "File uploaded and linked successfully"
          },
          "400": {
            "description": "Invalid request or no file uploaded"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Upload file and link to document",
        "tags": [
          "Document Linking"
        ]
      }
    },
    "/documents/{document_id}": {
      "delete": {
        "description": "Soft delete a document by setting deleted_at timestamp.\n\n## J-GAAP Compliance\nThis endpoint implements soft deletion for audit trail preservation:\n- Sets `is_deleted: true` and `deleted_at` timestamp\n- Records `deleted_by` user ID\n- Document is preserved in database for 7-10 year retention\n- Published and locked documents cannot be deleted (use void instead)\n\n## 電子帳簿保存法 Compliance\nPer Japanese Electronic Books Preservation Act:\n- Documents must be retained for minimum 7 years\n- All operations must be logged for audit trail\n- Deleted documents remain accessible for tax audits\n\n## Use Cases\n- Draft document cleanup\n- Document management\n- Reversible deletion\n\n## Important\nPublished documents that are locked should be voided, not deleted.\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the document to delete",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DeleteDocumentResponse"
                }
              }
            },
            "description": "Document deleted successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Published documents cannot be deleted. Use void for accounting compliance.",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Cannot delete published/locked document"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Soft delete a document (J-GAAP compliant)",
        "tags": [
          "Documents"
        ]
      },
      "get": {
        "description": "Retrieve a specific document by its unique identifier.\n\n## Path Parameters\n- **document_id**: UUID of the document to retrieve\n\n## Response Data\nReturns complete document information including:\n- Document metadata (name, type, status)\n- Content structure and data\n- Version and lock information\n- Audit timestamps\n\n## Document Access\n- Only returns documents owned by the authenticated user\n- Includes all document types and statuses\n- Provides complete document structure\n- Includes version and history metadata\n\n## Use Cases\n- Document detail views\n- Document editing forms\n- Content display and rendering\n- Document management operations\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the document to retrieve",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DocumentResponse"
                }
              }
            },
            "description": "Document retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "ACCESS_DENIED",
                      "type": "string"
                    },
                    "error": {
                      "example": "Access denied",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Access denied - document belongs to different user"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get document by ID",
        "tags": [
          "Documents"
        ]
      },
      "put": {
        "description": "Update an existing document with new content, name, or status.\n\n## Path Parameters\n- **document_id**: UUID of the document to update\n\n## Request Body\nAll fields are optional for updates:\n- **document_name**: New document name\n- **content**: Updated document content (structured JSON)\n- **status**: New document status (draft, published, archived)\n\n## Update Behavior\n- Only provided fields are updated\n- Omitted fields remain unchanged\n- Content is replaced entirely if provided\n- Version number is incremented\n- Update timestamp is refreshed\n\n## Status Transitions\nValid status transitions:\n- **draft** → **published** (confirmation)\n- **published** → **archived** (archival)\n- **draft** → **archived** (cancellation)\n\n## Validation\n- Document must exist and belong to user\n- Status transitions must be valid\n- Content must be valid JSON if provided\n- Name length restrictions apply\n\n## Locked documents (訂正)\nChanging the **content** of a locked document is a 訂正 and needs a reason in\n`X-Document-Change-Reason` (8+ characters); without one the request is refused\nwith **428** `DOCUMENT_LOCKED` (`details.kind = document_change_reason_required`).\nThe alternative is to unlock first (`PATCH /documents/{document_id}/lock`). The\nreason is recorded in the document audit log's `change_reason`. Re-sending the\nstored content unchanged, and any edit of an unlocked document, need no reason.\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the document to update",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Why a locked document is corrected (訂正理由). Required to change a locked document’s content.",
            "in": "header",
            "name": "X-Document-Change-Reason",
            "required": false,
            "schema": {
              "minLength": 8,
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateDocumentRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DocumentResponse"
                }
              }
            },
            "description": "Document updated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "ACCESS_DENIED",
                      "type": "string"
                    },
                    "error": {
                      "example": "Access denied",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Access denied - document belongs to different user"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "428": {
            "description": "The document is locked and the content changed without an X-Document-Change-Reason (8+ characters)"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update document",
        "tags": [
          "Documents"
        ]
      }
    },
    "/documents/{document_id}/activities": {
      "get": {
        "description": "Retrieve the complete activity/audit log for a document.\n\n## Activity Types Tracked\n| Action | Description |\n|--------|-------------|\n| created | Document was created |\n| updated | Document content was modified |\n| locked | Document was locked |\n| unlocked | Document was unlocked |\n| deleted | Document was soft deleted |\n| restored | Document was restored from deletion |\n| voided | Document was voided |\n| duplicated | Document was created from duplication |\n| status_changed | Document status was changed |\n\n## J-GAAP Compliance\nThis endpoint provides the audit trail required for:\n- 電子帳簿保存法 compliance\n- Tax audit support\n- Internal controls\n- Change history tracking\n\n## Query Parameters\n- **limit**: Number of activities to return (default: 50)\n- **offset**: Pagination offset (default: 0)\n\n## Response\nReturns activities with:\n- Action type and timestamp\n- User who performed the action\n- Version number\n- Metadata (diff, reasons, etc.)\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the document",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Number of activities to return",
            "in": "query",
            "name": "limit",
            "required": false,
            "schema": {
              "default": 50,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "description": "Pagination offset",
            "in": "query",
            "name": "offset",
            "required": false,
            "schema": {
              "default": 0,
              "minimum": 0,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DocumentActivityResponse"
                }
              }
            },
            "description": "Document activities retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get document activity log (audit trail)",
        "tags": [
          "Documents"
        ]
      }
    },
    "/documents/{document_id}/attachments": {
      "get": {
        "description": "Retrieve all attachments associated with a specific document.\n\n## Path Parameters\n- **document_id**: UUID of the document to get attachments for\n\n## Attachment Information\nReturns array of attachments with:\n- File metadata (name, size, type)\n- Download URLs for file access\n- Upload timestamps\n- Unique attachment identifiers\n\n## File Access\n- Download URLs are pre-signed for security\n- URLs may have expiration times\n- Access is restricted to document owner\n- File types and sizes are validated\n\n## Use Cases\n- Document detail views\n- File download interfaces\n- Attachment management\n- Document completeness verification\n\n## Security\nOnly returns attachments for documents belonging to the authenticated user.\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the document to get attachments for",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DocumentAttachmentsResponse"
                }
              }
            },
            "description": "Document attachments retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "ACCESS_DENIED",
                      "type": "string"
                    },
                    "error": {
                      "example": "Access denied",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Access denied - document belongs to different user"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get document attachments",
        "tags": [
          "Documents"
        ]
      }
    },
    "/documents/{document_id}/available": {
      "get": {
        "description": "\nGet documents that can be linked to a source document (not already linked).\n\n**Filters (camelCase, auto-converted):**\n- `documentType`: Filter by type (receipt, invoice, all)\n- `search`: Search by document name or vendor name\n- `limit`: Max results (default: 50, max: 100)\n- `offset`: Pagination offset\n\n**Returns documents with:**\n- Basic info (id, name, documentType)\n- Extracted content (amount, vendor, date)\n- Pagination metadata\n      ",
        "operationId": "getAvailableDocumentsForLinking",
        "parameters": [
          {
            "description": "Source document UUID",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Filter by document type (camelCase, auto-converted)",
            "in": "query",
            "name": "documentType",
            "required": false,
            "schema": {
              "enum": [
                "receipt",
                "invoice",
                "expense_receipt",
                "travel_receipt",
                "all"
              ],
              "type": "string"
            }
          },
          {
            "description": "Search term for document name or vendor",
            "in": "query",
            "name": "search",
            "required": false,
            "schema": {
              "maxLength": 100,
              "type": "string"
            }
          },
          {
            "description": "Max results",
            "in": "query",
            "name": "limit",
            "required": false,
            "schema": {
              "default": 50,
              "maximum": 100,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "description": "Pagination offset",
            "in": "query",
            "name": "offset",
            "required": false,
            "schema": {
              "default": 0,
              "minimum": 0,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "documents": {
                          "items": {
                            "properties": {
                              "amount": {
                                "description": "In `currency`.",
                                "type": "number"
                              },
                              "amountJpy": {
                                "description": "amount in yen; null when foreign and no rate is known",
                                "example": 1962,
                                "nullable": true,
                                "type": "number"
                              },
                              "createdAt": {
                                "format": "date-time",
                                "type": "string"
                              },
                              "currency": {
                                "description": "ISO currency of amount",
                                "example": "USD",
                                "type": "string"
                              },
                              "documentType": {
                                "type": "string"
                              },
                              "id": {
                                "format": "uuid",
                                "type": "string"
                              },
                              "issueDate": {
                                "type": "integer"
                              },
                              "name": {
                                "type": "string"
                              },
                              "vendorName": {
                                "type": "string"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        },
                        "hasMore": {
                          "type": "boolean"
                        },
                        "limit": {
                          "type": "integer"
                        },
                        "offset": {
                          "type": "integer"
                        },
                        "total": {
                          "type": "integer"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Available documents retrieved successfully"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get available documents for linking",
        "tags": [
          "Document Linking"
        ]
      }
    },
    "/documents/{document_id}/bank-link-candidates": {
      "get": {
        "description": "For a 金銭消費貸借契約書（役員借入金） (`contract_loan_exec`): the bank transactions already\nlinked to it, and — while none is — the deposits that could be the loan: inbound, exactly the loan\namount, within ±30 days of the contract date, not linked to another loan contract, and not booked to\nany account but 役員借入金 (238). The payer of the owner's earlier loan deposits ranks first.\nOther document types return `applicable: false`. Read-only.",
        "parameters": [
          {
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "applicable": {
                          "type": "boolean"
                        },
                        "candidates": {
                          "items": {
                            "additionalProperties": false,
                            "properties": {
                              "amount": {
                                "type": "number"
                              },
                              "bankTransactionId": {
                                "format": "uuid",
                                "type": "string"
                              },
                              "daysFromContract": {
                                "type": "integer"
                              },
                              "description": {
                                "nullable": true,
                                "type": "string"
                              },
                              "hasJournalEntry": {
                                "type": "boolean"
                              },
                              "samePayerAsPreviousLoans": {
                                "type": "boolean"
                              },
                              "transactionDate": {
                                "type": "integer"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        },
                        "contractDate": {
                          "description": "YYYYMMDD",
                          "nullable": true,
                          "type": "integer"
                        },
                        "linked": {
                          "items": {
                            "additionalProperties": false,
                            "properties": {
                              "amount": {
                                "type": "number"
                              },
                              "bankTransactionId": {
                                "format": "uuid",
                                "type": "string"
                              },
                              "description": {
                                "nullable": true,
                                "type": "string"
                              },
                              "hasJournalEntry": {
                                "type": "boolean"
                              },
                              "transactionDate": {
                                "nullable": true,
                                "type": "integer"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        },
                        "loanAmount": {
                          "nullable": true,
                          "type": "number"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Linked deposits and candidates"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Document not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Deposits that can back a 役員借入金 contract",
        "tags": [
          "Documents"
        ]
      }
    },
    "/documents/{document_id}/buyer-attachments": {
      "get": {
        "description": "Retrieve buyer attachments for a document.\n\n## Buyer Attachments in Japanese B2B\nIn Japanese B2B transactions, buyers send:\n- **発注書 (Purchase Order)**: After accepting a quotation\n- **納品書 (Delivery Note)**: Sometimes buyers send their own delivery confirmation\n\nThese documents are uploaded as attachments to the seller's invoice or quotation.\n\n## Query Parameters\n- **type**: Filter by attachment type (purchase_order, delivery_note, other, all)\n\n## Response\nReturns array of buyer attachments with file details.\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the document",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Filter by attachment type (発注書 = purchase_order, 納品書 = delivery_note)",
            "in": "query",
            "name": "type",
            "required": false,
            "schema": {
              "default": "all",
              "enum": [
                "purchase_order",
                "delivery_note",
                "other",
                "all"
              ],
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BuyerAttachmentsResponse"
                }
              }
            },
            "description": "Buyer attachments retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get buyer attachments (発注書/納品書)",
        "tags": [
          "Documents"
        ]
      },
      "post": {
        "description": "Upload a buyer attachment to a document.\n\n## Workflow\n1. First upload the file using `POST /api/files/upload`\n2. Then link it to the document using this endpoint\n\n## Attachment Types\n- **purchase_order**: 発注書 (Purchase Order from buyer)\n- **delivery_note**: 納品書 (Delivery Note from buyer)\n- **other**: Other buyer documents\n\n## Request Body\n- **fileUploadId**: UUID of the previously uploaded file\n- **attachmentType**: Type of buyer attachment\n- **description**: Optional description\n- **metadata**: Optional additional metadata\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the document to attach to",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UploadBuyerAttachmentRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/UploadBuyerAttachmentResponse"
                }
              }
            },
            "description": "Buyer attachment uploaded successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Upload buyer attachment (発注書/納品書)",
        "tags": [
          "Documents"
        ]
      }
    },
    "/documents/{document_id}/buyer-attachments/{attachment_id}": {
      "delete": {
        "description": "Delete a buyer attachment from a document.\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the document",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "UUID of the buyer attachment to delete",
            "in": "path",
            "name": "attachment_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "deletedId": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "success": {
                          "example": true,
                          "type": "boolean"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Buyer attachment deleted successfully",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Buyer attachment deleted successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Delete buyer attachment",
        "tags": [
          "Documents"
        ]
      }
    },
    "/documents/{document_id}/client": {
      "patch": {
        "description": "Link a trading partner (client) to a document for the Japanese B2B sales workflow.\n\n## Purpose\nEstablishes a direct relationship between documents and trading partners for:\n- 見積書 → 発注書 → 納品書 → 請求書 workflow tracking\n- Client-based document filtering and statistics\n- Trading partner relationship management\n\n## Link Methods\nDocuments can be linked to clients via:\n1. **Direct FK (client_id)** - Preferred, this endpoint sets this\n2. **JSONB content** - Legacy, via clientInfo.companyName field\n\n## Request Body\n- **clientId**: UUID of the client to link, or null/omit to unlink\n\n## Response\nReturns the updated document with embedded client info:\n- document.client: Full client object if linked\n- document.client_id: Client UUID if linked, null if unlinked\n\n## Use Cases\n- Link client when starting a new quotation workflow\n- Link client after selecting from client modal\n- Unlink client to reassign document to different client\n- Automatic linking during document creation\n\n## Authentication\nRequires valid Bearer token. Both document and client must belong to the authenticated user.",
        "parameters": [
          {
            "description": "UUID of the document",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "link-client": {
                  "summary": "Link a client to document",
                  "value": {
                    "clientId": "550e8400-e29b-41d4-a716-446655440000"
                  }
                },
                "unlink-client": {
                  "summary": "Unlink client from document",
                  "value": {
                    "clientId": null
                  }
                }
              },
              "schema": {
                "properties": {
                  "clientId": {
                    "description": "UUID of client to link, or null to unlink",
                    "example": "550e8400-e29b-41d4-a716-446655440000",
                    "format": "uuid",
                    "nullable": true,
                    "type": "string"
                  }
                },
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "client": {
                          "nullable": true,
                          "properties": {
                            "address": {
                              "type": "string"
                            },
                            "client_type": {
                              "description": "0=Customer, 1=Supplier, 2=Both",
                              "type": "number"
                            },
                            "contact_person": {
                              "type": "string"
                            },
                            "corporate_number": {
                              "example": "1234567890123",
                              "type": "string"
                            },
                            "email": {
                              "type": "string"
                            },
                            "furigana": {
                              "example": "カブシキガイシャサンプル",
                              "type": "string"
                            },
                            "id": {
                              "format": "uuid",
                              "type": "string"
                            },
                            "name": {
                              "example": "株式会社サンプル",
                              "type": "string"
                            },
                            "phone": {
                              "type": "string"
                            },
                            "registration_number": {
                              "example": "T1234567890123",
                              "type": "string"
                            }
                          },
                          "type": "object"
                        },
                        "client_id": {
                          "format": "uuid",
                          "nullable": true,
                          "type": "string"
                        },
                        "document_name": {
                          "type": "string"
                        },
                        "document_type": {
                          "type": "string"
                        },
                        "id": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "updated_at": {
                          "format": "date-time",
                          "type": "string"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Client linked to document successfully",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Document-client link updated successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Document not found or access denied",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 404,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Document or client not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Link or unlink a client (trading partner) to a document",
        "tags": [
          "Documents"
        ]
      }
    },
    "/documents/{document_id}/confirm": {
      "put": {
        "description": "Confirm a draft document and change its status to published.\n\n## Path Parameters\n- **document_id**: UUID of the document to confirm\n\n## Confirmation Process\nThis endpoint:\n- Changes document status from 'draft' to 'published'\n- Locks the document for editing (is_locked = true)\n- Triggers any associated business logic\n- Creates version history entry\n- May generate related records (invoices, journal entries, etc.)\n\n## Document Processing\nDepending on document type, confirmation may trigger:\n- **Sales Invoice**: Journal entry generation\n- **Claims**: Expense processing\n- **Service Agreement**: Contract activation\n- **Company Info**: Profile updates\n\n## Status Requirements\n- Document must be in 'draft' status\n- Document must belong to authenticated user\n- Document content must be valid and complete\n\n## Irreversible Action\nOnce confirmed:\n- Document becomes read-only (locked)\n- Status cannot be changed back to draft\n- Content modifications are restricted\n- Only archival is possible\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the document to confirm",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DocumentResponse"
                }
              }
            },
            "description": "Document confirmed and published successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "INVALID_STATUS",
                      "type": "string"
                    },
                    "error": {
                      "example": "Document cannot be confirmed",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Document cannot be confirmed (not in draft status or invalid content)"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "ACCESS_DENIED",
                      "type": "string"
                    },
                    "error": {
                      "example": "Access denied",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Access denied - document belongs to different user"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Confirm and publish document",
        "tags": [
          "Documents"
        ]
      }
    },
    "/documents/{document_id}/duplicate": {
      "post": {
        "description": "Create a copy of an existing document for use as a template.\n\n## Duplication Behavior\n- Creates new document with same type and structure\n- New document is always in 'draft' status\n- New document is unlocked and editable\n- Generates new UUID\n\n## Optional Overrides\n- **document_name**: Custom name (defaults to \"Original Name (コピー)\")\n- **content**: Override content if needed\n\n## Use Cases\n- Creating similar invoices quickly\n- Template-based document creation\n- Cloning documents for editing\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the document to duplicate",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/DuplicateDocumentRequest"
              }
            }
          },
          "required": false
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DuplicateDocumentResponse"
                }
              }
            },
            "description": "Document duplicated successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Duplicate a document as a template",
        "tags": [
          "Documents"
        ]
      }
    },
    "/documents/{document_id}/full": {
      "get": {
        "description": "**Composite endpoint** to fetch a document with all related data in a single request.\n\n## Purpose\nReduces 5-6 API round trips to 1 for document detail views, significantly improving frontend performance.\n\n## Query Parameters (camelCase supported - middleware auto-converts)\n| Parameter | Default | Description |\n|-----------|---------|-------------|\n| `include_linked_docs` | `true` | Include linked documents (relationships, receipts) |\n| `include_attachments` | `true` | Include document attachments |\n| `include_expenses` | `true` | Include expense references (for claims documents) |\n| `include_dock` | `false` | Include reimbursement dock data (workflow) |\n| `include_bank_links` | `false` | Include bank transaction links (reconciliation) |\n\n## Frontend Optimization\nInstead of calling these endpoints separately:\n- `GET /api/documents/:id`\n- `GET /api/documents/:id/attachments`\n- `GET /api/expenses/document/:id`\n- `GET /api/reconciliation/links`\n\nCall this single endpoint with appropriate includes:\n```\nGET /api/documents/:id/full?includeLinkedDocs=true&includeAttachments=true&includeExpenses=true&includeDock=true\n```\n\n## Response Structure\n```json\n{\n  \"success\": true,\n  \"data\": {\n    \"document\": { /* Full document data */ },\n    \"linked_docs\": [ /* Linked documents if requested */ ],\n    \"attachments\": [ /* Attachments if requested */ ],\n    \"expenses\": [ /* Expense references if requested (claims docs) */ ],\n    \"dock_data\": { /* Reimbursement workflow if requested */ },\n    \"bank_links\": [ /* Bank links if requested */ ],\n    \"_meta\": {\n      \"included_fields\": [\"document\", \"linked_docs\", \"attachments\", \"expenses\"],\n      \"fetch_time_ms\": 145\n    }\n  }\n}\n```\n\n## Performance\n- **Before**: ~2700ms (5-6 sequential API calls)\n- **After**: ~150-300ms (1 parallel call)\n- **Improvement**: ~89% latency reduction\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the document to retrieve",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Include linked documents (relationships, receipts, etc.)",
            "in": "query",
            "name": "include_linked_docs",
            "required": false,
            "schema": {
              "default": true,
              "type": "boolean"
            }
          },
          {
            "description": "Include document attachments",
            "in": "query",
            "name": "include_attachments",
            "required": false,
            "schema": {
              "default": true,
              "type": "boolean"
            }
          },
          {
            "description": "Include expense references (for claims documents). Same data as GET /api/expenses/document/:id",
            "in": "query",
            "name": "include_expenses",
            "required": false,
            "schema": {
              "default": true,
              "type": "boolean"
            }
          },
          {
            "description": "Include reimbursement dock data (for travel/claims/payment workflow documents)",
            "in": "query",
            "name": "include_dock",
            "required": false,
            "schema": {
              "default": false,
              "type": "boolean"
            }
          },
          {
            "description": "Include bank transaction links (for reconciliation)",
            "in": "query",
            "name": "include_bank_links",
            "required": false,
            "schema": {
              "default": false,
              "type": "boolean"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "_meta": {
                          "properties": {
                            "fetch_time_ms": {
                              "description": "Time taken to fetch all data in milliseconds",
                              "example": 145,
                              "type": "number"
                            },
                            "included_fields": {
                              "example": [
                                "document",
                                "linked_docs",
                                "attachments",
                                "expenses"
                              ],
                              "items": {
                                "type": "string"
                              },
                              "type": "array"
                            }
                          },
                          "type": "object"
                        },
                        "attachments": {
                          "description": "Document attachments (if include_attachments=true)",
                          "items": {
                            "properties": {
                              "file_name": {
                                "type": "string"
                              },
                              "file_type": {
                                "type": "string"
                              },
                              "file_url": {
                                "type": "string"
                              },
                              "id": {
                                "format": "uuid",
                                "type": "string"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        },
                        "bank_links": {
                          "description": "Bank transaction links (if include_bank_links=true)",
                          "items": {
                            "type": "object"
                          },
                          "type": "array"
                        },
                        "dock_data": {
                          "description": "Reimbursement dock data (if include_dock=true). Same card shapes as\n`GET /api/reimbursement/{document_id}/dock`. v5.20+ (VR-08): every card carries `hasInkan`, salary slips\ncarry `reimbursementNetPay` (差引支給額) and payments carry `contentAmount`, so the dock no longer fetches\neach chain document to derive them.",
                          "properties": {
                            "claimsDocuments": {
                              "items": {
                                "$ref": "#/components/schemas/ClaimsDocumentSummary"
                              },
                              "type": "array"
                            },
                            "currentDocument": {
                              "type": "object"
                            },
                            "paymentDocuments": {
                              "items": {
                                "$ref": "#/components/schemas/PaymentDocumentSummary"
                              },
                              "type": "array"
                            },
                            "salarySlipDocuments": {
                              "items": {
                                "$ref": "#/components/schemas/SalarySlipDocumentSummary"
                              },
                              "type": "array"
                            },
                            "totalReimbursementAmount": {
                              "type": "number"
                            },
                            "travelReport": {
                              "$ref": "#/components/schemas/TravelReportSummary"
                            },
                            "workflowActions": {
                              "type": "array"
                            }
                          },
                          "type": "object"
                        },
                        "document": {
                          "$ref": "#/components/schemas/Document",
                          "description": "Full document data"
                        },
                        "expenses": {
                          "description": "Expense references for claims documents (if include_expenses=true)",
                          "items": {
                            "properties": {
                              "allocationRate": {
                                "type": "number"
                              },
                              "amount": {
                                "type": "number"
                              },
                              "attachments": {
                                "items": {
                                  "type": "object"
                                },
                                "type": "array"
                              },
                              "category": {
                                "type": "string"
                              },
                              "currency": {
                                "type": "string"
                              },
                              "date": {
                                "format": "date-time",
                                "type": "string"
                              },
                              "id": {
                                "format": "uuid",
                                "type": "string"
                              },
                              "paymentMethod": {
                                "type": "string"
                              },
                              "purpose": {
                                "type": "string"
                              },
                              "remarks": {
                                "type": "string"
                              },
                              "taxCategory": {
                                "type": "string"
                              },
                              "vendor": {
                                "type": "string"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        },
                        "linked_docs": {
                          "description": "Linked documents (if include_linked_docs=true)",
                          "items": {
                            "type": "object"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Document full data retrieved successfully",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Document with all related data retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get document with all related data (v4.33+)",
        "tags": [
          "Documents"
        ]
      }
    },
    "/documents/{document_id}/history": {
      "get": {
        "description": "Retrieve the version history and change log for a specific document.\n\n## Path Parameters\n- **document_id**: UUID of the document to get history for\n\n## Query Parameters\n- **page_number**: Page number for pagination (default: 1)\n- **page_size**: Number of history entries per page (default: 20)\n\n## Sort Order\nResults are **guaranteed sorted by version number descending** (newest first).\nFrontend can rely on `versions[0]` being the most recent entry.\n\n## Version History\nReturns list of lifecycle events from the `version_control` table:\n- Document version numbers (sequential, no gaps)\n- `change_type` values: `confirmed`, `locked`, `unlocked`, `deleted`, `restored`, `voided`, `duplicated`\n- Modification timestamps (`changed_at`)\n- User who made the change (`changed_by`)\n\n## Change Tracking\nHistory includes lifecycle events:\n- **confirmed** — Document published (PUT /confirm)\n- **locked** / **unlocked** — Lock state toggled (PATCH /lock)\n- **deleted** — Soft-deleted\n- **restored** — Restored from soft-delete\n- **voided** — J-GAAP void (accounting cancellation)\n- **duplicated** — Document copied as template\n\n**Note:** Auto-save and content edits do NOT create version entries.\nOnly lifecycle state changes are tracked.\n\n## Pagination\nHistory entries are paginated for performance:\n- Newest version first (descending)\n- Configurable page sizes\n- Navigation metadata included\n\n## Use Cases\n- Audit trails and compliance (操作履歴)\n- Change tracking and review\n- Version comparison (future: requires content snapshots)\n- Document forensics\n\n## Security\nOnly returns history for documents belonging to the authenticated user.\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the document to get history for",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Page number for pagination",
            "in": "query",
            "name": "page_number",
            "required": false,
            "schema": {
              "default": 1,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "description": "Number of history entries per page",
            "in": "query",
            "name": "page_size",
            "required": false,
            "schema": {
              "default": 20,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DocumentHistoryResponse"
                }
              }
            },
            "description": "Document history retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "ACCESS_DENIED",
                      "type": "string"
                    },
                    "error": {
                      "example": "Access denied",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Access denied - document belongs to different user"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get document version history",
        "tags": [
          "Documents"
        ]
      }
    },
    "/documents/{document_id}/history/{version}": {
      "get": {
        "description": "Retrieve a specific version's content snapshot from the version history.\n\n## Path Parameters\n- **document_id**: UUID of the document\n- **version**: Version number (integer, starts at 1)\n\n## Response\nReturns the version entry with its full content snapshot in the `content` field.\nIf the version was created before content snapshots were enabled, `hasContent` will be false and `content` will be `{}`.\n\n## Use Cases\n- View past version content in a modal/diff view\n- Preview before restoring to an older version\n- Audit trail with full document state\n\n## Security\nOnly returns versions for documents belonging to the authenticated user.",
        "parameters": [
          {
            "description": "UUID of the document",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Version number to retrieve",
            "in": "path",
            "name": "version",
            "required": true,
            "schema": {
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "changeType": {
                          "enum": [
                            "confirmed",
                            "locked",
                            "unlocked",
                            "deleted",
                            "restored",
                            "voided",
                            "duplicated",
                            "version_restored"
                          ],
                          "type": "string"
                        },
                        "changedAt": {
                          "format": "date-time",
                          "type": "string"
                        },
                        "changedBy": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "content": {
                          "description": "Full document state snapshot (content, status, metadata, etc.). Empty {} for pre-snapshot versions.",
                          "properties": {
                            "content": {
                              "description": "Document JSONB content",
                              "type": "object"
                            },
                            "document_name": {
                              "type": "string"
                            },
                            "document_type": {
                              "type": "string"
                            },
                            "is_locked": {
                              "type": "boolean"
                            },
                            "metadata": {
                              "type": "object"
                            },
                            "status": {
                              "type": "string"
                            }
                          },
                          "type": "object"
                        },
                        "createdAt": {
                          "format": "date-time",
                          "type": "string"
                        },
                        "documentId": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "hasContent": {
                          "description": "Whether this version has a content snapshot",
                          "type": "boolean"
                        },
                        "id": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "label": {
                          "description": "Human-readable version label",
                          "nullable": true,
                          "type": "string"
                        },
                        "metadata": {
                          "type": "object"
                        },
                        "reason": {
                          "nullable": true,
                          "type": "string"
                        },
                        "version": {
                          "example": 3,
                          "type": "integer"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Document version retrieved successfully",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Version retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get single version content snapshot",
        "tags": [
          "Documents"
        ]
      }
    },
    "/documents/{document_id}/link": {
      "post": {
        "description": "\nLink one or more documents to a source document.\n\n**Request body (camelCase - auto-converted to snake_case):**\n- `documents`: Array of documents to link\n  - `documentId`: UUID of the document to link\n  - `relationshipType`: Type of relationship (optional, default: receipt_attachment)\n  - `allocatedAmount`: Optional amount to allocate\n  - `note`: Optional note\n\n**Works with any document type** - claims, travel reports, salary slips, etc.\n      ",
        "operationId": "linkDocumentsToDocument",
        "parameters": [
          {
            "description": "Source document UUID",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "example": {
                "documents": [
                  {
                    "allocatedAmount": 5000,
                    "documentId": "550e8400-e29b-41d4-a716-446655440001",
                    "relationshipType": "receipt_attachment"
                  },
                  {
                    "allocatedAmount": 30000,
                    "documentId": "550e8400-e29b-41d4-a716-446655440002",
                    "note": "出張先での宿泊費",
                    "relationshipType": "invoice_attachment"
                  }
                ]
              },
              "schema": {
                "properties": {
                  "documents": {
                    "description": "Array of documents to link (send camelCase)",
                    "items": {
                      "properties": {
                        "allocatedAmount": {
                          "description": "Amount to allocate from this document",
                          "type": "number"
                        },
                        "documentId": {
                          "description": "Document UUID to link",
                          "format": "uuid",
                          "type": "string"
                        },
                        "note": {
                          "description": "Optional note",
                          "maxLength": 500,
                          "type": "string"
                        },
                        "relationshipType": {
                          "default": "receipt_attachment",
                          "description": "Type of relationship",
                          "enum": [
                            "receipt_attachment",
                            "invoice_attachment",
                            "supporting_document",
                            "related_document"
                          ],
                          "type": "string"
                        }
                      },
                      "required": [
                        "documentId"
                      ],
                      "type": "object"
                    },
                    "minItems": 1,
                    "type": "array"
                  }
                },
                "required": [
                  "documents"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "linkIds": {
                          "items": {
                            "format": "uuid",
                            "type": "string"
                          },
                          "type": "array"
                        },
                        "linkedCount": {
                          "example": 2,
                          "type": "integer"
                        },
                        "success": {
                          "example": true,
                          "type": "boolean"
                        },
                        "warnings": {
                          "items": {
                            "type": "string"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Successfully linked 2 document(s)",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Documents linked successfully"
          },
          "207": {
            "description": "Partial success - some documents linked with warnings"
          },
          "400": {
            "description": "Invalid request body"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Document not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Link documents to any document",
        "tags": [
          "Document Linking"
        ]
      }
    },
    "/documents/{document_id}/linked-documents": {
      "get": {
        "description": "\nRetrieve all documents linked to a source document (claims, travel reports, salary slips, etc.).\n\n**Queries BOTH tables:**\n- `document_relationships` - New generic linking\n- `expense_claim_receipts` - Legacy expense claim links\n\n**Response includes (camelCase):**\n- `linkedDocuments`: All linked documents (merged from both tables)\n- `linkedInvoices`: Linked invoice documents (filtered)\n- `linkedReceipts`: Linked receipt/payment documents (filtered)\n- `linkedDocumentCount`: Total count of all linked documents\n- `totalAllocatedAmount`: Sum of all allocated amounts\n\n**Works with any document type** - not limited to expense claims.\n      ",
        "operationId": "getDocumentLinkedDocuments",
        "parameters": [
          {
            "description": "Source document UUID (any document type)",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Filter by relationship type (camelCase, auto-converted)",
            "in": "query",
            "name": "relationshipType",
            "required": false,
            "schema": {
              "enum": [
                "receipt_attachment",
                "invoice_attachment",
                "supporting_document",
                "related_document",
                "source_document",
                "generated_from"
              ],
              "type": "string"
            }
          },
          {
            "description": "Include full document details",
            "in": "query",
            "name": "includeDetails",
            "required": false,
            "schema": {
              "default": false,
              "type": "boolean"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "example": {
                  "data": {
                    "documentId": "550e8400-e29b-41d4-a716-446655440000",
                    "documentName": "2024年3月出張報告書",
                    "documentType": "travel_report",
                    "linkedDocumentCount": 1,
                    "linkedDocuments": [
                      {
                        "allocatedAmount": 14000,
                        "amount": 14000,
                        "documentType": "travel_receipt",
                        "id": "550e8400-e29b-41d4-a716-446655440001",
                        "linkId": "550e8400-e29b-41d4-a716-446655440010",
                        "linkedAt": "2024-03-20T10:00:00Z",
                        "name": "新幹線切符",
                        "relationshipType": "receipt_attachment",
                        "vendorName": "JR東日本"
                      }
                    ],
                    "linkedInvoices": [],
                    "linkedReceipts": [
                      {
                        "allocatedAmount": 14000,
                        "amount": 14000,
                        "documentType": "travel_receipt",
                        "id": "550e8400-e29b-41d4-a716-446655440001",
                        "linkId": "550e8400-e29b-41d4-a716-446655440010",
                        "linkedAt": "2024-03-20T10:00:00Z",
                        "name": "新幹線切符",
                        "relationshipType": "receipt_attachment",
                        "vendorName": "JR東日本"
                      }
                    ],
                    "totalAllocatedAmount": 14000
                  },
                  "message": "Linked documents retrieved successfully",
                  "success": true
                },
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "documentId": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "documentName": {
                          "example": "2024年3月出張報告書",
                          "type": "string"
                        },
                        "documentType": {
                          "example": "travel_report",
                          "type": "string"
                        },
                        "linkedDocumentCount": {
                          "example": 5,
                          "type": "integer"
                        },
                        "linkedDocuments": {
                          "items": {
                            "$ref": "#/components/schemas/GenericLinkedDocument"
                          },
                          "type": "array"
                        },
                        "linkedInvoices": {
                          "items": {
                            "$ref": "#/components/schemas/GenericLinkedDocument"
                          },
                          "type": "array"
                        },
                        "linkedReceipts": {
                          "items": {
                            "$ref": "#/components/schemas/GenericLinkedDocument"
                          },
                          "type": "array"
                        },
                        "totalAllocatedAmount": {
                          "example": 45000,
                          "type": "number"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Linked documents retrieved successfully"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Document not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get linked documents for any document",
        "tags": [
          "Document Linking"
        ]
      }
    },
    "/documents/{document_id}/lock": {
      "patch": {
        "description": "Toggle the lock status of a document.\n\n## Path Parameters\n- **document_id**: UUID of the document to lock/unlock\n\n## Request Body\n- **isLocked**: Boolean - set to true to lock, false to unlock\n\n## Lock Behavior\nWhen locking a document:\n- Sets is_locked to true\n- Records locked_at timestamp\n- Records locked_by user ID\n- Document becomes read-only (edits prevented)\n\nWhen unlocking a document:\n- Sets is_locked to false\n- Clears locked_at timestamp\n- Clears locked_by user ID\n- Document becomes editable again\n\n## Use Cases\n- **Manual locking**: User explicitly locks a finalized document\n- **Confirm endpoint**: Automatically locks document on finalization\n- **Unlocking**: Admin or owner can unlock for corrections\n\n## Important Notes\n- Only the document owner can lock/unlock their documents\n- Renaming does NOT lock documents (renamed for clarity only)\n- The confirm endpoint automatically locks documents\n- Frontend should check is_locked before allowing edits\n\n## Response\nReturns the updated document lock status including:\n- id: Document UUID\n- isLocked: Current lock state\n- lockedAt: Timestamp when locked (null if unlocked)\n- lockedBy: User UUID who locked (null if unlocked)\n- updatedAt: Last update timestamp\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the document to lock/unlock",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/LockDocumentRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LockDocumentResponse"
                }
              }
            },
            "description": "Document lock status updated successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "ACCESS_DENIED",
                      "type": "string"
                    },
                    "error": {
                      "example": "Access denied",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Access denied - document belongs to different user"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Lock or unlock a document",
        "tags": [
          "Documents"
        ]
      }
    },
    "/documents/{document_id}/relationships": {
      "get": {
        "description": "Retrieve all relationships for a document, supporting the Japanese B2B workflow.\n\n## Japanese B2B Document Flow (売り手視点)\nStandard document flow in Japanese B2B transactions:\n\n| Step | Document | Japanese | Direction |\n|------|----------|----------|-----------|\n| 1 | Quotation | 見積書 | Seller → Buyer |\n| 2 | Purchase Order | 発注書 | Buyer → Seller |\n| 3 | Delivery Note | 納品書 | Both directions |\n| 4 | Invoice | 請求書 | Seller → Buyer |\n\n## Relationship Types\n\n| Type | Description | Example |\n|------|-------------|---------|\n| quotation_to_order | 見積書 → 発注書 | Quote accepted, order placed |\n| order_to_delivery | 発注書 → 納品書 | Order fulfilled |\n| delivery_to_invoice | 納品書 → 請求書 | Delivery completed, billing |\n| quotation_to_invoice | 見積書 → 請求書 | Direct billing from quote |\n| buyer_attachment | 発注書/納品書 as file | File from buyer |\n| references | General reference | Loose document link |\n\n## Query Parameters\n- **relationshipType**: Filter by specific type\n- **direction**: Filter by parent/child/both\n- **limit**: Pagination limit (default: 50)\n- **offset**: Pagination offset (default: 0)\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the document",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Filter by relationship type",
            "in": "query",
            "name": "relationship_type",
            "required": false,
            "schema": {
              "enum": [
                "quotation_to_order",
                "order_to_delivery",
                "delivery_to_invoice",
                "quotation_to_invoice",
                "buyer_attachment",
                "supporting_document",
                "revision_of",
                "supersedes",
                "references",
                "related_to"
              ],
              "type": "string"
            }
          },
          {
            "description": "Filter by relationship direction",
            "in": "query",
            "name": "direction",
            "required": false,
            "schema": {
              "default": "both",
              "enum": [
                "parent",
                "child",
                "both"
              ],
              "type": "string"
            }
          },
          {
            "description": "Pagination limit",
            "in": "query",
            "name": "limit",
            "required": false,
            "schema": {
              "default": 50,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "description": "Pagination offset",
            "in": "query",
            "name": "offset",
            "required": false,
            "schema": {
              "default": 0,
              "minimum": 0,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DocumentRelationshipsResponse"
                }
              }
            },
            "description": "Document relationships retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get document relationships (Japanese B2B workflow)",
        "tags": [
          "Documents"
        ]
      },
      "post": {
        "description": "Create a relationship between two documents for Japanese B2B workflow.\n\n## Use Cases\n- Link 見積書 to 請求書 (quotation_to_invoice)\n- Link 発注書 to 納品書 (order_to_delivery)\n- Reference related documents (references)\n\n## Validation\n- Both documents must exist and belong to the user\n- Self-referencing is not allowed\n- Duplicate relationships are rejected\n\n## Request Body\n- **childDocumentId**: UUID of the document to link as child\n- **relationshipType**: Type of relationship\n- **relationshipMetadata**: Optional additional metadata\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the parent document",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateDocumentRelationshipRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CreateDocumentRelationshipResponse"
                }
              }
            },
            "description": "Document relationship created successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Relationship already exists between these documents",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Relationship already exists"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create document relationship (link documents)",
        "tags": [
          "Documents"
        ]
      }
    },
    "/documents/{document_id}/relationships/{relationship_id}": {
      "delete": {
        "description": "Delete a relationship between documents.\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the document",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "UUID of the relationship to delete",
            "in": "path",
            "name": "relationship_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "deletedId": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "success": {
                          "example": true,
                          "type": "boolean"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Document relationship deleted successfully",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Document relationship deleted successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Delete document relationship",
        "tags": [
          "Documents"
        ]
      }
    },
    "/documents/{document_id}/rename": {
      "put": {
        "description": "Change the name of an existing document.\n\n## Path Parameters\n- **document_id**: UUID of the document to rename\n\n## Request Body\n- **document_name**: New name for the document (required)\n\n## Rename Operation\nThis endpoint:\n- Updates only the document name\n- Preserves all other document properties\n- Updates the modification timestamp\n- Maintains version history\n- Validates name length and format\n\n## Name Validation\n- Name must not be empty\n- Maximum length restrictions apply\n- Special characters may be restricted\n- Duplicate names are allowed\n\n## Use Cases\n- Correcting document names\n- Improving document organization\n- Updating document titles\n- Content management operations\n\n## Security\nOnly allows renaming of documents belonging to the authenticated user.\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the document to rename",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/RenameDocumentRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DocumentResponse"
                }
              }
            },
            "description": "Document renamed successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "ACCESS_DENIED",
                      "type": "string"
                    },
                    "error": {
                      "example": "Access denied",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Access denied - document belongs to different user"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Rename document",
        "tags": [
          "Documents"
        ]
      }
    },
    "/documents/{document_id}/restore": {
      "post": {
        "description": "Restore a previously soft-deleted document.\n\n## Restore Behavior\n- Sets `is_deleted: false`\n- Clears `deleted_at` and `deleted_by`\n- Logs restore activity for audit trail\n\n## Use Cases\n- Recovering accidentally deleted documents\n- Reversing deletion decisions\n- Admin document recovery\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the document to restore",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RestoreDocumentResponse"
                }
              }
            },
            "description": "Document restored successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Document is not deleted",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Document is not deleted"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Restore a soft-deleted document",
        "tags": [
          "Documents"
        ]
      }
    },
    "/documents/{document_id}/restore-version/{version}": {
      "post": {
        "description": "Restore the document content to a specific version's snapshot.\n\n## Path Parameters\n- **document_id**: UUID of the document\n- **version**: Version number to restore to\n\n## Request Body (optional)\n- **reason**: Optional reason for the restore\n\n## Preconditions\n- Document must NOT be locked (unlock first)\n- Document must NOT be voided\n- Document must NOT be deleted (restore from trash first)\n- Target version must have a content snapshot (`hasContent: true`)\n\n## What Happens\n1. Reads the content snapshot from the target version\n2. Overwrites the current document content with the snapshot\n3. Creates a new version entry with `change_type: \"version_restored\"`\n4. The new version entry includes the restored content as its snapshot\n\n## J-GAAP Compliance\nPublished documents that are locked cannot be restored -- they must be unlocked first.\nThis prevents accidental modification of confirmed accounting documents.\n\n## Security\nOnly the document owner can restore versions.",
        "parameters": [
          {
            "description": "UUID of the document",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Version number to restore to",
            "in": "path",
            "name": "version",
            "required": true,
            "schema": {
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "reason": {
                    "description": "Optional reason for the restore",
                    "example": "税務確認前の状態に戻す",
                    "maxLength": 500,
                    "type": "string"
                  }
                },
                "type": "object"
              }
            }
          },
          "required": false
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "documentName": {
                          "type": "string"
                        },
                        "id": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "restoredFromVersion": {
                          "type": "integer"
                        },
                        "status": {
                          "type": "string"
                        },
                        "updatedAt": {
                          "format": "date-time",
                          "type": "string"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Document restored to version 3 successfully",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Document restored to version successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "enum": [
                        "DOCUMENT_LOCKED",
                        "DOCUMENT_VOIDED",
                        "DOCUMENT_DELETED",
                        "VERSION_NO_CONTENT"
                      ],
                      "type": "string"
                    },
                    "error": {
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Cannot restore -- document locked, voided, deleted, or version has no content"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Restore document to a past version",
        "tags": [
          "Documents"
        ]
      }
    },
    "/documents/{document_id}/unlink/{link_id}": {
      "delete": {
        "description": "Remove the link between two documents.",
        "operationId": "unlinkDocumentFromDocument",
        "parameters": [
          {
            "description": "Source document UUID",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Link record UUID to remove",
            "in": "path",
            "name": "link_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "success": {
                          "example": true,
                          "type": "boolean"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Document unlinked successfully",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Document unlinked successfully"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Link not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Unlink document from source",
        "tags": [
          "Document Linking"
        ]
      }
    },
    "/documents/{document_id}/void": {
      "post": {
        "description": "Void a document for accounting compliance purposes.\n\n## J-GAAP Compliance\nFor accounting documents (invoices, journals, etc.) that cannot be deleted:\n- Marks document as voided with timestamp\n- Records void reason for audit trail\n- Automatically locks the document\n- Preserves all original data\n\n## When to Use Void vs Delete\n| Scenario | Action |\n|----------|--------|\n| Draft documents | Use DELETE |\n| Published invoices | Use VOID |\n| Issued accounting docs | Use VOID |\n| Test/unused documents | Use DELETE |\n\n## 電子帳簿保存法 Compliance\nVoided documents:\n- Cannot be edited or modified\n- Must include reason for voiding\n- Are preserved indefinitely for audit\n- Show in reports with \"voided\" status\n\n## Request Body\n- **reason**: Required explanation for voiding (max 500 chars)\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the document to void",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/VoidDocumentRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/VoidDocumentResponse"
                }
              }
            },
            "description": "Document voided successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Document is already voided",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Document already voided or deleted"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Void a document (J-GAAP compliant cancellation)",
        "tags": [
          "Documents"
        ]
      }
    },
    "/ebook/audit/{documentId}": {
      "get": {
        "description": "Get complete audit trail for a document as required by Japanese law.\n\n## Audit Trail Requirements (訂正削除履歴要件)\nComplete audit trail with:\n- **Action Logging**: Log all document actions (create, update, delete, view)\n- **User Tracking**: Track which user performed each action\n- **Timestamp Recording**: Record exact timestamp for each action\n- **Detail Preservation**: Preserve detailed information about each action\n- **Legal Compliance**: Meet 電子帳簿保存法 audit trail requirements\n- **Immutable Records**: Ensure audit records cannot be modified\n\n## Audit Actions Tracked\n- **Create**: Document creation and registration\n- **Update**: Document metadata or content updates\n- **Delete**: Document deletion (soft delete with audit trail)\n- **View**: Document viewing and access\n- **Download**: Document download and export\n- **Verify**: Timestamp verification attempts\n- **Timestamp**: Timestamp application to document\n\n## Audit Information\n- **Action Details**: Comprehensive details about each action\n- **User Information**: User who performed the action\n- **Timestamp**: Exact date and time of action\n- **IP Address**: IP address of user (when available)\n- **User Agent**: Browser/client information (when available)\n- **Previous Data**: Previous state for update actions\n- **New Data**: New state for update actions\n\n## Use Cases\n- **Legal Compliance**: Meet 電子帳簿保存法 audit requirements\n- **Audit Support**: Support internal and external audits\n- **Investigation**: Investigate document history and changes\n- **Compliance Verification**: Verify audit trail completeness\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Document ID to get audit trail for",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "in": "path",
            "name": "documentId",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AuditTrailResponse"
                }
              }
            },
            "description": "Audit trail retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get document audit trail (訂正削除履歴)",
        "tags": [
          "Electronic Book Preservation"
        ]
      }
    },
    "/ebook/compliance": {
      "get": {
        "description": "Check overall compliance status with Electronic Book Preservation Law.\n\n## Compliance Assessment (コンプライアンス評価)\nComprehensive compliance checking with:\n- **Overall Status**: Determine if system meets legal requirements\n- **Compliance Score**: Numerical score (0-100) indicating compliance level\n- **Issue Identification**: Identify specific compliance issues and gaps\n- **Severity Classification**: Classify issues by severity (critical, warning, info)\n- **Recommendations**: Provide specific recommendations to improve compliance\n- **Legal Standards**: Assess against 電子帳簿保存法 requirements\n\n## Compliance Criteria\n- **Document Registration**: Proper document registration with metadata\n- **Timestamp Coverage**: Adequate timestamp application to documents\n- **Search Functionality**: Legal search requirements implementation\n- **Audit Trail**: Complete audit trail maintenance\n- **File Integrity**: File integrity verification capabilities\n- **Storage Requirements**: Proper document storage and preservation\n\n## Assessment Results\n- **Compliance Status**: Overall compliance (compliant/non-compliant)\n- **Numerical Score**: 0-100 score based on compliance criteria\n- **Issue List**: Detailed list of compliance issues\n- **Recommendations**: Specific actions to improve compliance\n- **Assessment Date**: Timestamp of compliance assessment\n\n## Issue Severity Levels\n- **Critical**: Issues that prevent legal compliance\n- **Warning**: Issues that should be addressed for full compliance\n- **Info**: Informational items for compliance improvement\n\n## Use Cases\n- **Legal Compliance**: Verify compliance with 電子帳簿保存法\n- **Audit Preparation**: Prepare for compliance audits\n- **System Monitoring**: Monitor ongoing compliance status\n- **Improvement Planning**: Plan compliance improvement initiatives\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ComplianceResponse"
                }
              }
            },
            "description": "Compliance status retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Check compliance status (コンプライアンス状況確認)",
        "tags": [
          "Electronic Book Preservation"
        ]
      }
    },
    "/ebook/dashboard": {
      "get": {
        "description": "Get comprehensive compliance dashboard with statistics and analytics.\n\n## Compliance Dashboard (コンプライアンスダッシュボード)\nComprehensive dashboard with:\n- **Summary Statistics**: Overall document and compliance statistics\n- **Document Analysis**: Breakdown by document type and compliance status\n- **Recent Activity**: Recent audit log entries and system activity\n- **Compliance Alerts**: Active compliance alerts and warnings\n- **Trend Analysis**: Compliance trends and progress tracking\n- **Performance Metrics**: System performance and compliance metrics\n\n## Dashboard Components\n- **Document Summary**: Total, timestamped, and compliant document counts\n- **Compliance Rate**: Overall compliance rate percentage\n- **Type Breakdown**: Document statistics by type (receipt, invoice, etc.)\n- **Timestamp Coverage**: Timestamp application coverage by document type\n- **Recent Audit Logs**: Most recent document actions and changes\n- **Active Alerts**: Current compliance alerts requiring attention\n\n## Summary Statistics\n- **Total Documents**: Total number of registered documents\n- **Timestamped Documents**: Number of documents with timestamps\n- **Compliant Documents**: Number of fully compliant documents\n- **Compliance Rate**: Overall compliance rate percentage\n\n## Alert Types\n- **Critical Alerts**: Issues requiring immediate attention\n- **Warning Alerts**: Issues that should be addressed soon\n- **Informational**: General compliance information and tips\n\n## Use Cases\n- **Management Overview**: Provide management with compliance overview\n- **Operational Monitoring**: Monitor day-to-day compliance operations\n- **Trend Analysis**: Analyze compliance trends and improvements\n- **Alert Management**: Manage and respond to compliance alerts\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DashboardResponse"
                }
              }
            },
            "description": "Compliance dashboard retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get compliance dashboard (コンプライアンスダッシュボード)",
        "tags": [
          "Electronic Book Preservation"
        ]
      }
    },
    "/ebook/health": {
      "get": {
        "description": "Check the health and availability of the Electronic Book Preservation Law API.\n\n## Health Check Features\nAPI health monitoring with:\n- **Service Status**: Verify API service availability\n- **Feature Overview**: List available compliance features\n- **System Information**: Basic system health information\n- **Compliance Readiness**: Verify compliance system readiness\n\n## Available Features\n- **Document Registration**: Register documents with compliance metadata\n- **Timestamp Management**: タイムスタンプ付与・検証機能\n- **Legal Search**: 法定検索要件対応 (date, amount, vendor)\n- **Audit Trail**: 訂正削除履歴管理\n- **Compliance Checking**: コンプライアンス状況確認\n\n## Use Cases\n- **System Monitoring**: Monitor API health and availability\n- **Feature Discovery**: Discover available compliance features\n- **Integration Testing**: Test API connectivity and basic functionality\n- **Service Verification**: Verify service is ready for compliance operations\n\nNo authentication required for health check.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/EBookHealthResponse"
                }
              }
            },
            "description": "API health check successful"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "Health check for Electronic Book Preservation API",
        "tags": [
          "Electronic Book Preservation"
        ]
      }
    },
    "/ebook/register": {
      "post": {
        "description": "Register a document for Electronic Book Preservation Law compliance.\n\n## Document Registration (文書登録)\nComprehensive document registration with:\n- **Compliance Metadata**: Register document with legal compliance metadata\n- **Document Classification**: Classify document type for legal requirements\n- **Transaction Information**: Record transaction date, amount, and vendor\n- **File Integrity**: Calculate and store SHA-256 hash for authenticity\n- **Legal Requirements**: Ensure compliance with 電子帳簿保存法 requirements\n- **Audit Trail**: Automatic audit log creation for registration\n\n## Legal Requirements (法的要件)\n- **Document Type Classification**: Proper classification for legal compliance\n- **Transaction Data**: Date, amount, vendor name (法定検索要件)\n- **File Integrity**: SHA-256 hash for authenticity verification\n- **Storage Requirements**: Proper storage URL and file name recording\n- **Metadata Compliance**: Complete metadata for legal preservation\n\n## Document Types\n- **Receipt (領収書)**: Payment receipts and proof of payment\n- **Invoice (請求書)**: Sales and purchase invoices\n- **Contract (契約書)**: Business contracts and agreements\n- **Quotation (見積書)**: Price quotations and estimates\n- **Delivery Slip (納品書)**: Delivery and shipment documents\n- **Bank Statement (銀行取引明細)**: Bank transaction records\n- **Credit Card (クレジットカード明細)**: Credit card statements\n- **Electronic Mail (電子メール取引)**: Email-based transactions\n- **EDI (EDI取引データ)**: Electronic Data Interchange transactions\n- **Other (その他)**: Other business documents\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/RegisterDocumentRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/EBookDocumentResponse"
                }
              }
            },
            "description": "Document registered successfully for compliance"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Register document for compliance (文書登録)",
        "tags": [
          "Electronic Book Preservation"
        ]
      }
    },
    "/ebook/search": {
      "get": {
        "description": "Search documents according to Japanese Electronic Book Preservation Law requirements.\n\n## Legal Search Requirements (法定検索要件)\nMandatory search functionality with:\n- **Date Search (日付検索)**: Search by transaction date range\n- **Amount Search (金額検索)**: Search by transaction amount range\n- **Vendor Search (取引先検索)**: Search by vendor/payee name\n- **Document Type Filter**: Filter by document type classification\n- **Timestamp Status**: Filter by timestamp application status\n- **Full-Text Search**: Search document descriptions and content\n- **Pagination Support**: Handle large result sets with pagination\n\n## Legal Compliance (法的コンプライアンス)\nSearch functionality must support:\n- **Three Key Criteria**: Date (日付), Amount (金額), Vendor (取引先)\n- **Exact Match**: Support exact date and amount matching\n- **Partial Match**: Support partial vendor name matching\n- **Range Search**: Support date and amount range searches\n- **Result Accuracy**: Ensure search results are complete and accurate\n- **Performance**: Meet legal requirements for search response time\n\n## Search Parameters\n- **Date Range**: Start and end dates in YYYYMMDD format\n- **Amount Range**: Minimum and maximum transaction amounts\n- **Vendor Name**: Partial or exact vendor name matching\n- **Document Type**: Filter by specific document types\n- **Timestamp Status**: Filter timestamped or non-timestamped documents\n- **Text Search**: Full-text search in descriptions\n- **Pagination**: Page number and page size for result management\n\n## Use Cases\n- **Legal Compliance**: Meet 電子帳簿保存法 search requirements\n- **Audit Support**: Support audit and investigation requirements\n- **Document Discovery**: Find specific documents for business operations\n- **Compliance Verification**: Verify search functionality meets legal standards\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Start date in YYYYMMDD format",
            "in": "query",
            "name": "start_date",
            "required": false,
            "schema": {
              "example": 20240301,
              "type": "integer"
            }
          },
          {
            "description": "End date in YYYYMMDD format",
            "in": "query",
            "name": "end_date",
            "required": false,
            "schema": {
              "example": 20240331,
              "type": "integer"
            }
          },
          {
            "description": "Minimum transaction amount",
            "in": "query",
            "name": "min_amount",
            "required": false,
            "schema": {
              "example": 1000,
              "minimum": 0,
              "type": "number"
            }
          },
          {
            "description": "Maximum transaction amount",
            "in": "query",
            "name": "max_amount",
            "required": false,
            "schema": {
              "example": 500000,
              "minimum": 0,
              "type": "number"
            }
          },
          {
            "description": "Vendor name (partial match supported)",
            "in": "query",
            "name": "vendor_name",
            "required": false,
            "schema": {
              "example": "株式会社",
              "type": "string"
            }
          },
          {
            "description": "Filter by document type",
            "in": "query",
            "name": "document_type",
            "required": false,
            "schema": {
              "$ref": "#/components/schemas/EBookDocumentType"
            }
          },
          {
            "description": "Filter by timestamp status",
            "in": "query",
            "name": "has_timestamp",
            "required": false,
            "schema": {
              "example": true,
              "type": "boolean"
            }
          },
          {
            "description": "Full-text search in descriptions",
            "in": "query",
            "name": "search_text",
            "required": false,
            "schema": {
              "example": "office supplies",
              "type": "string"
            }
          },
          {
            "description": "Page number for pagination",
            "in": "query",
            "name": "page",
            "required": false,
            "schema": {
              "default": 1,
              "example": 1,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "description": "Number of items per page",
            "in": "query",
            "name": "page_size",
            "required": false,
            "schema": {
              "default": 20,
              "example": 20,
              "maximum": 100,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DocumentSearchResponse"
                }
              }
            },
            "description": "Document search completed successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Search documents with legal requirements (法定検索)",
        "tags": [
          "Electronic Book Preservation"
        ]
      }
    },
    "/ebook/timestamp": {
      "post": {
        "description": "Add a trusted timestamp to a document for legal authenticity.\n\n## Timestamp Management (タイムスタンプ管理)\nLegal timestamp application with:\n- **Trusted Timestamps**: Apply legally valid timestamps (タイムスタンプ)\n- **File Integrity**: Calculate SHA-256 hash for file verification\n- **Token Generation**: Generate timestamp tokens for verification\n- **Legal Validity**: Ensure timestamps meet Japanese legal requirements\n- **Authenticity Assurance**: Provide proof of document authenticity at specific time\n- **Audit Trail**: Complete audit logging for timestamp application\n\n## Legal Requirements (法的要件)\n- **Timestamp Authority**: Integration with trusted timestamp authorities (TSA)\n- **Hash Calculation**: SHA-256 hash for file integrity verification\n- **Token Storage**: Secure storage of timestamp tokens\n- **Verification Support**: Enable future timestamp verification\n- **Audit Compliance**: Complete audit trail for legal compliance\n\n## Timestamp Process\n1. **File Upload**: Provide document file (base64 encoded)\n2. **Hash Calculation**: Calculate SHA-256 hash for integrity\n3. **Timestamp Generation**: Generate trusted timestamp token\n4. **Storage**: Store timestamp metadata with document\n5. **Verification**: Enable future timestamp verification\n\n## Use Cases\n- **Legal Compliance**: Meet 電子帳簿保存法 timestamp requirements\n- **Document Authenticity**: Prove document authenticity at specific time\n- **Audit Trail**: Maintain complete audit trail for compliance\n- **Integrity Verification**: Enable future file integrity verification\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/TimestampRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/TimestampResponse"
                }
              }
            },
            "description": "Timestamp added successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Add timestamp to document (タイムスタンプ付与)",
        "tags": [
          "Electronic Book Preservation"
        ]
      }
    },
    "/ebook/verify": {
      "post": {
        "description": "Verify the integrity and authenticity of a timestamped document.\n\n## Timestamp Verification (タイムスタンプ検証)\nComprehensive timestamp verification with:\n- **File Integrity Check**: Verify file has not been modified since timestamp\n- **Hash Verification**: Compare current file hash with stored hash\n- **Token Validation**: Validate timestamp token authenticity\n- **Legal Compliance**: Ensure verification meets legal requirements\n- **Audit Trail**: Log verification attempts for compliance\n- **Tamper Detection**: Detect any file modifications or tampering\n\n## Verification Process\n1. **File Analysis**: Calculate current SHA-256 hash of file\n2. **Hash Comparison**: Compare with stored hash from timestamp\n3. **Token Validation**: Verify timestamp token authenticity\n4. **Integrity Assessment**: Determine if file has been modified\n5. **Result Generation**: Provide verification result and details\n\n## Verification Results\n- **Valid**: File integrity confirmed, no modifications detected\n- **Invalid**: File has been modified since timestamp application\n- **No Timestamp**: Document does not have a timestamp applied\n- **Verification Error**: Technical error during verification process\n\n## Use Cases\n- **Legal Verification**: Verify document authenticity for legal proceedings\n- **Audit Support**: Support audit requirements with integrity verification\n- **Compliance Check**: Verify compliance with preservation requirements\n- **Tamper Detection**: Detect unauthorized document modifications\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/TimestampVerifyRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/TimestampVerifyResponse"
                }
              }
            },
            "description": "Timestamp verification completed"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Verify timestamp integrity (タイムスタンプ検証)",
        "tags": [
          "Electronic Book Preservation"
        ]
      }
    },
    "/establishment-guide/companies": {
      "get": {
        "description": "Get establishment guide progress for all user's companies.\n\n## Multi-Company Overview\nComprehensive company progress overview with:\n- **All Companies**: Progress for all companies associated with user\n- **Progress Summary**: Summary of progress for each company formation\n- **Company Details**: Company names and identifiers for navigation\n- **Status Overview**: Quick overview of completion status per company\n- **Comparative Analytics**: Compare progress across multiple companies\n\n## Overview Features\n- **Consolidated View**: Single endpoint for all company progress\n- **Progress Comparison**: Compare completion rates across companies\n- **Navigation Support**: Company identifiers for detailed navigation\n- **Status Summary**: Quick status overview for dashboard displays\n- **Analytics Integration**: Aggregate analytics across all companies\n\nBearer token authentication required.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CompaniesProgressResponse"
                }
              }
            },
            "description": "All company progress retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get all company progress",
        "tags": [
          "Establishment Guide"
        ]
      }
    },
    "/establishment-guide/document-status": {
      "post": {
        "description": "Update document generation status and metadata.\n\n## Document Status Management\nComprehensive status updates with:\n- **Status Updates**: Update generation status with detailed information\n- **Error Reporting**: Report and track generation errors and issues\n- **Document Linking**: Associate generated documents with progress\n- **Metadata Updates**: Update document metadata and properties\n- **Progress Integration**: Integrate document status with step progress\n\n## Status Updates\n- **Generation Progress**: Update real-time generation progress\n- **Completion Notification**: Mark documents as completed with links\n- **Error Handling**: Report errors with detailed diagnostic information\n- **Version Updates**: Update document versions and modifications\n- **Access Control**: Manage document access and permissions\n\nBearer token authentication required.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateDocumentStatusRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DocumentStatusResponse"
                }
              }
            },
            "description": "Document status updated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update document generation status",
        "tags": [
          "Establishment Guide"
        ]
      }
    },
    "/establishment-guide/document-status/{documentType}": {
      "get": {
        "description": "Get status of document generation for specific document type.\n\n## Document Status Tracking\nComprehensive document management with:\n- **Generation Status**: Track document generation progress and completion\n- **Error Handling**: Detailed error information for failed generations\n- **Document Links**: Access to generated documents and downloads\n- **Version Control**: Track document versions and updates\n- **Status History**: Historical status changes and timestamps\n\n## Document Types\n- **articles_of_incorporation**: 定款 (Articles of Incorporation)\n- **business_plan**: 事業計画書 (Business Plan)\n- **capital_verification**: 資本金証明書 (Capital Verification)\n- **registration_application**: 登記申請書 (Registration Application)\n- **tax_notifications**: 税務届出書 (Tax Notifications)\n- **social_insurance_forms**: 社会保険関係書類 (Social Insurance Forms)\n\n## Status Information\n- **Generation Progress**: Real-time generation status and progress\n- **Error Details**: Comprehensive error information and resolution guidance\n- **Document Access**: Direct access to generated documents\n- **Timestamp Tracking**: Creation and modification timestamps\n- **Version Management**: Document version control and history\n\nBearer token authentication required.",
        "parameters": [
          {
            "description": "Type of document to check status",
            "example": "articles_of_incorporation",
            "in": "path",
            "name": "documentType",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DocumentStatusResponse"
                }
              }
            },
            "description": "Document status retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "DOCUMENT_NOT_FOUND",
                      "type": "string"
                    },
                    "error": {
                      "example": "Document not found",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Document not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get document generation status",
        "tags": [
          "Establishment Guide"
        ]
      }
    },
    "/establishment-guide/progress": {
      "delete": {
        "description": "Reset user's establishment guide progress to initial state.\n\n## Progress Reset\nComplete progress reset functionality with:\n- **Full Reset**: Reset all progress to initial state with default values\n- **Multi-Company Support**: Optional company-specific progress reset\n- **Data Cleanup**: Remove all step data, user context, and time tracking\n- **Document Cleanup**: Reset document generation status to initial state\n- **Analytics Preservation**: Maintain analytics data for reporting purposes\n\n## Reset Scope\n- **Default Progress**: Reset to system default progress state\n- **Step Completion**: Clear all completed steps and reset current step to 0\n- **User Context**: Reset user context to empty object\n- **Step Data**: Clear all step-specific data and user inputs\n- **Time Tracking**: Reset all step time tracking information\n- **Document Status**: Reset document generation status to 'not_started'\n\n## Multi-Company Reset\n- **Company-Specific**: Reset progress for specific company when company_id provided\n- **User-Wide**: Reset default progress when no company_id specified\n- **Isolation**: Company-specific resets don't affect other company progress\n- **Selective Reset**: Choose between resetting specific company or all progress\n\n## Use Cases\n- **Start Over**: Allow users to completely restart the establishment process\n- **Company Switch**: Reset progress when switching between different companies\n- **Error Recovery**: Reset progress after encountering data corruption issues\n- **Testing**: Reset progress for testing and development purposes\n- **Clean Slate**: Provide fresh start for users who want to begin again\n\n## Safety Considerations\n- **Irreversible Action**: Progress reset cannot be undone\n- **Data Loss**: All progress data will be permanently lost\n- **Confirmation Required**: Frontend should implement confirmation dialogs\n- **Audit Trail**: Reset actions should be logged for audit purposes\n- **Backup Strategy**: Consider implementing progress backup before reset\n\nBearer token authentication required.",
        "parameters": [
          {
            "description": "Optional company ID for company-specific reset",
            "example": "comp_123456",
            "in": "query",
            "name": "company_id",
            "required": false,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/EstablishmentProgress"
                    },
                    "message": {
                      "example": "Progress reset successfully",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    },
                    "timestamp": {
                      "example": "2024-01-15T10:30:00Z",
                      "format": "date-time",
                      "type": "string"
                    }
                  },
                  "required": [
                    "success",
                    "message",
                    "data",
                    "timestamp"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Progress reset successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "COMPANY_NOT_FOUND",
                      "type": "string"
                    },
                    "error": {
                      "example": "Company not found",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Company not found (when company_id specified)"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Reset establishment guide progress",
        "tags": [
          "Establishment Guide"
        ]
      },
      "get": {
        "description": "Load user's establishment guide progress for company formation tracking.\n\n## Progress Management\nComprehensive progress tracking with:\n- **Current Step Index**: Track current position in 18-step establishment process\n- **Completed Steps**: Array of completed step indices with validation\n- **User Context**: Company details, business type, and formation preferences\n- **Step Data**: Detailed form data and user inputs for each step\n- **Multi-Company Support**: Separate progress tracking for multiple companies\n- **Time Tracking**: Step-level timing for analytics and optimization\n\n## 18 Establishment Steps\nComplete Japanese company formation process:\n1. **COMPANY_TYPE**: Company structure selection (株式会社 vs 合同会社)\n2. **BUSINESS_PURPOSE**: Business purpose definition for articles\n3. **COMPANY_NAME**: Company name selection and trademark check\n4. **VIRTUAL_OFFICE**: Registered address and office setup\n5. **COMPANY_SEAL**: Corporate seal creation and registration\n6. **CAPITAL_PLANNING**: Capital structure and amount planning\n7. **ARTICLES_OF_INCORPORATION**: Articles drafting and filing\n8. **CAPITAL_PAYMENT**: Capital payment and bank procedures\n9. **ELECTRONIC_CERTIFICATE**: Digital certificate acquisition\n10. **REGISTRATION_APPLICATION**: Legal entity registration\n11. **SEAL_REGISTRATION**: Official seal registration\n12. **LICENSES_PERMITS**: Industry licenses and permits\n13. **TAX_NOTIFICATIONS**: Tax office notifications\n14. **SOCIAL_INSURANCE**: Social insurance registration\n15. **CORPORATE_BANK_ACCOUNT**: Corporate banking setup\n16. **ACCOUNTING_SETUP**: Accounting system setup\n17. **BUSINESS_CARDS_WEBSITE**: Marketing materials\n18. **SUBSIDIES_GRANTS**: Government subsidies and grants\n\n## Progress Features\n- **Auto-Save**: Automatic progress saving with debouncing\n- **Document Status**: Track generated documents and their status\n- **Time Analytics**: Step completion time tracking for optimization\n- **Multi-Company**: Support for multiple company formations per user\n- **Context Preservation**: Maintain user context across sessions\n- **Step Validation**: Ensure proper step completion and data integrity\n\n## Use Cases\n- **Formation Tracking**: Track progress through complex establishment process\n- **Multi-Business**: Manage multiple company formations simultaneously\n- **Document Management**: Track document generation and completion status\n- **Analytics**: Monitor user behavior and identify optimization opportunities\n- **Compliance**: Ensure all required steps are completed properly\n\nBearer token authentication required.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProgressResponse"
                }
              }
            },
            "description": "Progress loaded successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Load establishment guide progress",
        "tags": [
          "Establishment Guide"
        ]
      },
      "post": {
        "description": "Save user's establishment guide progress with auto-save functionality.\n\n## Progress Saving\nComprehensive progress persistence with:\n- **Step Completion**: Mark steps as completed with validation\n- **User Context**: Save company details and formation preferences\n- **Step Data**: Persist detailed form data and user inputs\n- **Auto-Save**: Debounced saving to prevent excessive database writes\n- **Validation**: Ensure data integrity and step completion requirements\n- **Timestamp Tracking**: Automatic timestamp updates for progress tracking\n\n## Data Persistence\n- **JSON Storage**: Flexible JSON storage in user_profiles.preferences\n- **Multi-Company**: Company-specific progress isolation and management\n- **Context Preservation**: Maintain user context across sessions and devices\n- **Incremental Updates**: Efficient updates for modified data only\n- **Backup Strategy**: Automatic backup of previous progress states\n- **Conflict Resolution**: Handle concurrent updates gracefully\n\n## Validation Rules\n- **Step Sequence**: Ensure proper step progression and dependencies\n- **Required Fields**: Validate required fields for each step\n- **Data Integrity**: Ensure consistent data across related steps\n- **Business Rules**: Apply Japanese business formation requirements\n- **Context Validation**: Validate user context for consistency\n- **Progress Validation**: Ensure logical progress state transitions\n\n## Use Cases\n- **Form Persistence**: Save form data as users progress through steps\n- **Session Management**: Preserve progress across browser sessions\n- **Multi-Device**: Sync progress across multiple devices\n- **Backup Recovery**: Recover progress from previous states\n- **Analytics**: Track user behavior and completion patterns\n\nBearer token authentication required.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/SaveProgressRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProgressResponse"
                }
              }
            },
            "description": "Progress saved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Save establishment guide progress",
        "tags": [
          "Establishment Guide"
        ]
      }
    },
    "/establishment-guide/progress/company/{companyId}": {
      "get": {
        "description": "Load establishment guide progress for a specific company.\n\n## Multi-Company Support\nCompany-specific progress tracking with:\n- **Isolated Progress**: Separate progress tracking for each company formation\n- **Company Context**: Company-specific context and configuration\n- **Independent Tracking**: Independent step completion and timing\n- **Document Management**: Company-specific document generation and status\n- **Analytics Separation**: Separate analytics and reporting per company\n\n## Company Progress Features\n- **Dedicated Storage**: Company-specific progress storage and retrieval\n- **Context Isolation**: Isolated user context per company formation\n- **Step Independence**: Independent step completion tracking\n- **Document Tracking**: Company-specific document status and management\n- **Time Analytics**: Company-specific timing and performance metrics\n\nBearer token authentication required.",
        "parameters": [
          {
            "description": "Company identifier",
            "example": "comp_123456",
            "in": "path",
            "name": "companyId",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProgressResponse"
                }
              }
            },
            "description": "Company progress loaded successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "COMPANY_NOT_FOUND",
                      "type": "string"
                    },
                    "error": {
                      "example": "Company not found",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Company not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Load company-specific progress",
        "tags": [
          "Establishment Guide"
        ]
      },
      "post": {
        "description": "Save establishment guide progress for a specific company.\n\n## Company-Specific Saving\nDedicated progress persistence with:\n- **Company Isolation**: Save progress specific to company formation\n- **Independent Context**: Maintain separate context per company\n- **Dedicated Storage**: Company-specific storage and retrieval\n- **Document Association**: Link documents to specific company formation\n- **Analytics Tracking**: Company-specific analytics and performance tracking\n\nBearer token authentication required.",
        "parameters": [
          {
            "description": "Company identifier",
            "example": "comp_123456",
            "in": "path",
            "name": "companyId",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/SaveProgressRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProgressResponse"
                }
              }
            },
            "description": "Company progress saved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "COMPANY_NOT_FOUND",
                      "type": "string"
                    },
                    "error": {
                      "example": "Company not found",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Company not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Save company-specific progress",
        "tags": [
          "Establishment Guide"
        ]
      }
    },
    "/establishment-guide/step-tracking/complete": {
      "post": {
        "description": "Record when user completes a specific establishment step.\n\n## Step Completion Tracking\nComprehensive completion analytics with:\n- **Completion Timestamps**: Record precise step completion times\n- **Duration Calculation**: Calculate time spent on each step\n- **Success Metrics**: Track successful step completion rates\n- **Quality Metrics**: Measure completion quality and accuracy\n- **Progress Validation**: Validate step completion requirements\n\n## Completion Analytics\n- **Time Analysis**: Analyze time spent per step for optimization\n- **Success Rates**: Track completion success rates by step\n- **Quality Assessment**: Measure completion quality and accuracy\n- **User Patterns**: Identify successful completion patterns\n- **Optimization Insights**: Generate insights for process improvement\n\nBearer token authentication required.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/StepTrackingCompleteRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "message": {
                      "example": "Step completion event recorded",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    },
                    "timestamp": {
                      "example": "2024-01-15T10:30:00Z",
                      "format": "date-time",
                      "type": "string"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Step completion event recorded successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Record step completed event",
        "tags": [
          "Establishment Guide"
        ]
      }
    },
    "/establishment-guide/step-tracking/start": {
      "post": {
        "description": "Record when user starts working on a specific establishment step.\n\n## Step Time Tracking\nComprehensive timing analytics with:\n- **Start Timestamps**: Record precise step start times for analytics\n- **User Behavior**: Track user interaction patterns and engagement\n- **Performance Metrics**: Measure step completion times and efficiency\n- **Drop-off Analysis**: Identify steps where users abandon the process\n- **Optimization Data**: Collect data for user experience optimization\n\n## Analytics Benefits\n- **Funnel Analysis**: Understand user progression through establishment process\n- **Performance Optimization**: Identify slow or problematic steps\n- **User Experience**: Improve step design based on usage patterns\n- **Completion Prediction**: Predict completion likelihood based on behavior\n- **Resource Planning**: Allocate support resources based on usage data\n\nBearer token authentication required.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/StepTrackingStartRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "message": {
                      "example": "Step start event recorded",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    },
                    "timestamp": {
                      "example": "2024-01-15T10:30:00Z",
                      "format": "date-time",
                      "type": "string"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Step start event recorded successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Record step started event",
        "tags": [
          "Establishment Guide"
        ]
      }
    },
    "/establishment-guide/steps": {
      "get": {
        "description": "Get comprehensive metadata for all 18 establishment steps.\n\n## Steps Metadata\nComplete step information with:\n- **Step Identification**: Unique step keys and indices for navigation\n- **Multilingual Titles**: English and Japanese titles for internationalization\n- **Descriptions**: Detailed descriptions of step requirements and objectives\n- **Categories**: Step categorization for logical grouping and navigation\n- **Time Estimates**: Realistic time estimates for planning and expectation setting\n- **Cost Estimates**: Cost information for budgeting and financial planning\n\n## Step Categories\n- **事前準備 (Preparation)**: Initial planning and decision-making steps\n- **定款作成 (Articles)**: Articles of incorporation and legal document preparation\n- **登記手続き (Registration)**: Official registration and legal procedures\n- **事後手続き (Post-Registration)**: Post-registration setup and compliance\n- **運営準備 (Operations)**: Business operations setup and preparation\n\n## Metadata Features\n- **Comprehensive Information**: Complete step details for informed decision-making\n- **Planning Support**: Time and cost estimates for project planning\n- **Progress Tracking**: Step indices for progress calculation and navigation\n- **Localization**: Japanese and English titles for multilingual support\n- **Category Organization**: Logical grouping for better user experience\n\n## Use Cases\n- **Step Navigation**: Build step-by-step navigation interfaces\n- **Progress Visualization**: Create progress bars and completion indicators\n- **Planning Tools**: Provide time and cost estimates for planning\n- **Documentation**: Generate step-by-step guides and documentation\n- **Localization**: Support multilingual establishment guides\n\nNo authentication required for metadata access.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/StepsMetadataResponse"
                }
              }
            },
            "description": "Steps metadata retrieved successfully"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "Get establishment steps metadata",
        "tags": [
          "Establishment Guide"
        ]
      }
    },
    "/exchange-rates": {
      "get": {
        "description": "Retrieve exchange rates for a specific date from the local database cache only.\n\n## Database-Only Retrieval\nReturns cached exchange rates with:\n- **Local Database Query**: Retrieves rates from local database cache only\n- **No External API Calls**: Does not fetch from external APIs if rates are missing\n- **Fast Response**: Optimized for quick retrieval from cached data\n- **Date-Specific**: Returns all available rates for the specified date\n- **Currency Coverage**: Includes all currency pairs available for the date\n\n## Rate Information\n- **Currency Pairs**: All available FROM/TO currency combinations\n- **Rate Precision**: Decimal precision for accurate financial calculations\n- **Source Tracking**: Indicates whether rates are manual, API-sourced, or bank-fed\n- **Provider Information**: Shows which external provider supplied the rates\n- **Timestamp Data**: Creation and update timestamps for rate tracking\n\n## Use Cases\n- **Quick Rate Lookup**: Fast retrieval of cached exchange rates\n- **Financial Calculations**: Get rates for expense and invoice calculations\n- **Historical Analysis**: Retrieve rates for past dates from cache\n- **System Integration**: Provide rates to other financial systems\n- **Report Generation**: Include current rates in financial reports\n\n## Response Behavior\n- **200 OK**: Returns exchange rates if found in database\n- **404 Not Found**: No rates in cache for the date NOR for any of the 14 days before it. A weekend, a holiday or a day the cron has not reached yet answers 200 with the latest earlier day's rows (each row carries its own rate_date).\n- **No External Fetch**: Will not attempt to fetch from external APIs\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Date for exchange rates in YYYYMMDD format",
            "example": 20240115,
            "in": "query",
            "name": "date",
            "required": true,
            "schema": {
              "maximum": 20991231,
              "minimum": 20000101,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful_retrieval": {
                    "summary": "Successful rate retrieval",
                    "value": {
                      "data": {
                        "base_currency": "JPY",
                        "date": 20240115,
                        "last_updated": "2024-01-15T10:30:00.000Z",
                        "rates": [
                          {
                            "created_at": "2024-01-15T10:30:00.000Z",
                            "created_by": "abc12345-def6-7890-ghij-klmnopqrstuv",
                            "from_currency": "USD",
                            "id": "123e4567-e89b-12d3-a456-426614174000",
                            "is_active": true,
                            "provider": "fixer.io",
                            "rate": 150.25,
                            "rate_date": 20240115,
                            "source": "external_api",
                            "to_currency": "JPY",
                            "updated_at": "2024-01-15T10:30:00.000Z"
                          },
                          {
                            "created_at": "2024-01-15T10:30:00.000Z",
                            "created_by": "abc12345-def6-7890-ghij-klmnopqrstuv",
                            "from_currency": "EUR",
                            "id": "456e7890-f12a-34b5-c678-901234567890",
                            "is_active": true,
                            "provider": "fixer.io",
                            "rate": 163.45,
                            "rate_date": 20240115,
                            "source": "external_api",
                            "to_currency": "JPY",
                            "updated_at": "2024-01-15T10:30:00.000Z"
                          }
                        ],
                        "total_rates": 15
                      },
                      "message": "Exchange rates retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ExchangeRateResponse"
                }
              }
            },
            "description": "Exchange rates retrieved successfully from database"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Date must be a number in YYYYMMDD format",
                      "type": "string"
                    },
                    "fieldErrors": {
                      "additionalProperties": {
                        "items": {
                          "type": "string"
                        },
                        "type": "array"
                      },
                      "example": {
                        "date": [
                          "Date must be after 2000-01-01",
                          "Date must be before 2099-12-31"
                        ]
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid date parameter"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "example": null,
                      "type": "null"
                    },
                    "message": {
                      "example": "No exchange rates found for the specified date",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 404,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "No exchange rates found for the specified date"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get exchange rates from database",
        "tags": [
          "Exchange Rates"
        ]
      }
    },
    "/exchange-rates/currencies": {
      "post": {
        "description": "Retrieve exchange rates for specific currencies within a date range.\n\n## Currency-Specific Filtering\nTargeted rate retrieval with:\n- **Currency Selection**: Specify exact currencies needed for analysis\n- **Date Range Support**: Get rates across multiple dates for trend analysis\n- **Historical Data**: Access historical rates for specific currency pairs\n- **Efficient Queries**: Optimized database queries for selected currencies only\n- **Bulk Retrieval**: Get multiple currencies in a single request\n\n## Multi-Currency Analysis\n- **Currency Pairs**: Returns all combinations of specified currencies\n- **Rate History**: Historical rate progression for each currency pair\n- **Trend Analysis**: Data suitable for currency trend analysis\n- **Comparative Analysis**: Compare rates across different currencies\n- **Time Series Data**: Structured data for time series analysis\n\n## Use Cases\n- **Financial Reporting**: Get rates for specific currencies used in business\n- **Currency Analysis**: Analyze trends for particular currency pairs\n- **Risk Management**: Monitor exchange rate exposure for specific currencies\n- **Portfolio Management**: Track rates for investment portfolio currencies\n- **Compliance Reporting**: Generate reports for specific currency exposures\n\n## Request Optimization\n- **Selective Retrieval**: Only fetches data for requested currencies\n- **Date Range Limits**: Reasonable date range limits for performance\n- **Currency Limits**: Maximum number of currencies per request\n- **Efficient Processing**: Optimized queries for fast response times\n- **Data Formatting**: Structured response for easy consumption\n\n## Response Structure\n- **Currency Grouping**: Rates grouped by currency pair\n- **Historical Progression**: Chronological rate progression\n- **Source Information**: Provider and source details for each rate\n- **Date Coverage**: Clear indication of date range coverage\n- **Missing Data Handling**: Transparent handling of missing rate data\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "asian_currencies": {
                  "summary": "Asian currency rates",
                  "value": {
                    "currencies": [
                      "USD",
                      "CNY",
                      "KRW",
                      "SGD"
                    ],
                    "end_date": 20240131,
                    "start_date": 20240101
                  }
                },
                "major_currencies": {
                  "summary": "Major currency rates",
                  "value": {
                    "currencies": [
                      "USD",
                      "EUR",
                      "GBP"
                    ],
                    "end_date": 20240131,
                    "start_date": 20240101
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/GetExchangeRatesForCurrenciesRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "currency_rates": {
                    "summary": "Currency rate history",
                    "value": {
                      "data": [
                        {
                          "currency_pair": "USD/JPY",
                          "date_range": {
                            "end_date": 20240131,
                            "start_date": 20240101
                          },
                          "from_currency": "USD",
                          "rates": [
                            {
                              "date": 20240101,
                              "rate": 149.85,
                              "source": "external_api"
                            },
                            {
                              "date": 20240102,
                              "rate": 150.25,
                              "source": "external_api"
                            }
                          ],
                          "to_currency": "JPY"
                        },
                        {
                          "currency_pair": "EUR/JPY",
                          "date_range": {
                            "end_date": 20240131,
                            "start_date": 20240101
                          },
                          "from_currency": "EUR",
                          "rates": [
                            {
                              "date": 20240101,
                              "rate": 163.2,
                              "source": "external_api"
                            },
                            {
                              "date": 20240102,
                              "rate": 163.45,
                              "source": "external_api"
                            }
                          ],
                          "to_currency": "JPY"
                        }
                      ],
                      "message": "Currency rates retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/CurrencyRatesResponse"
                }
              }
            },
            "description": "Currency rates retrieved successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Start date must be before or equal to end date",
                      "type": "string"
                    },
                    "fieldErrors": {
                      "additionalProperties": {
                        "items": {
                          "type": "string"
                        },
                        "type": "array"
                      },
                      "example": {
                        "currencies": [
                          "At least one currency must be specified",
                          "Maximum 10 currencies allowed"
                        ]
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid request parameters"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get exchange rates for specific currencies",
        "tags": [
          "Exchange Rates"
        ]
      }
    },
    "/exchange-rates/fetch": {
      "post": {
        "description": "Retrieve exchange rates for a specific date, fetching from external API if not found in database.\n\n## Intelligent Rate Fetching\nSmart retrieval strategy with:\n- **Database First**: Checks local cache for existing rates\n- **External API Fallback**: Fetches from external API if rates not found locally\n- **Automatic Caching**: Saves fetched rates to database for future use\n- **Provider Integration**: Integrates with multiple exchange rate providers\n- **Real-Time Data**: Ensures up-to-date rates when needed\n\n## Fetching Process\n1. **Cache Check**: First checks local database for existing rates\n2. **External Fetch**: If not found, fetches from configured external API\n3. **Data Validation**: Validates fetched rates for accuracy and completeness\n4. **Cache Update**: Saves new rates to database for future retrieval\n5. **Response**: Returns rates with fetch status information\n\n## Provider Support\n- **Multiple Providers**: Support for various exchange rate APIs\n- **Provider Fallback**: Automatic fallback to secondary providers if primary fails\n- **Rate Validation**: Validates rates against reasonable ranges\n- **Error Handling**: Comprehensive error handling for API failures\n- **Rate Limiting**: Respects API rate limits and quotas\n\n## Use Cases\n- **Real-Time Calculations**: Get current rates for immediate financial calculations\n- **Cache Warming**: Pre-populate cache with rates for future use\n- **Data Freshness**: Ensure rates are current for critical financial operations\n- **System Integration**: Provide fresh rates to integrated financial systems\n- **Automated Processing**: Fetch rates as part of automated financial workflows\n\n## Response Information\n- **Fetch Status**: Indicates whether rates were fetched from external API\n- **Cache Status**: Shows whether local cache was updated\n- **Provider Info**: Identifies which provider supplied the rates\n- **Rate Freshness**: Timestamp information for rate currency\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Date for exchange rates in YYYYMMDD format",
            "example": 20240115,
            "in": "query",
            "name": "date",
            "required": true,
            "schema": {
              "maximum": 20991231,
              "minimum": 20000101,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "fetched_from_api": {
                    "summary": "Rates fetched from external API",
                    "value": {
                      "data": {
                        "cache_updated": true,
                        "fetched_from_external": true,
                        "rates": {
                          "base_currency": "JPY",
                          "date": 20240115,
                          "last_updated": "2024-01-15T10:30:00.000Z",
                          "rates": [
                            {
                              "created_at": "2024-01-15T10:30:00.000Z",
                              "created_by": "abc12345-def6-7890-ghij-klmnopqrstuv",
                              "from_currency": "USD",
                              "id": "123e4567-e89b-12d3-a456-426614174000",
                              "is_active": true,
                              "provider": "fixer.io",
                              "rate": 150.25,
                              "rate_date": 20240115,
                              "source": "external_api",
                              "to_currency": "JPY",
                              "updated_at": "2024-01-15T10:30:00.000Z"
                            }
                          ],
                          "total_rates": 15
                        }
                      },
                      "message": "Exchange rates fetched successfully",
                      "statusCode": 200
                    }
                  },
                  "found_in_cache": {
                    "summary": "Rates found in local cache",
                    "value": {
                      "data": {
                        "cache_updated": false,
                        "fetched_from_external": false,
                        "rates": {
                          "base_currency": "JPY",
                          "date": 20240115,
                          "last_updated": "2024-01-15T09:00:00.000Z",
                          "rates": [
                            {
                              "created_at": "2024-01-15T09:00:00.000Z",
                              "created_by": "abc12345-def6-7890-ghij-klmnopqrstuv",
                              "from_currency": "USD",
                              "id": "123e4567-e89b-12d3-a456-426614174000",
                              "is_active": true,
                              "provider": "fixer.io",
                              "rate": 150.25,
                              "rate_date": 20240115,
                              "source": "external_api",
                              "to_currency": "JPY",
                              "updated_at": "2024-01-15T09:00:00.000Z"
                            }
                          ],
                          "total_rates": 15
                        }
                      },
                      "message": "Exchange rates retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ExchangeRateFetchResponse"
                }
              }
            },
            "description": "Exchange rates fetched successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Date must be a number in YYYYMMDD format",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid date parameter"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          },
          "503": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Exchange rate service temporarily unavailable",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "External API unavailable"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Fetch exchange rates with external API fallback",
        "tags": [
          "Exchange Rates"
        ]
      }
    },
    "/exchange-rates/fetch-date-range": {
      "post": {
        "description": "Create a background job to fetch exchange rates for a specified date range.\n\n## Background Processing\nEfficient batch processing with:\n- **Background Jobs**: Creates queue job for processing large date ranges\n- **Progress Tracking**: Provides job ID for monitoring progress\n- **Batch Processing**: Processes multiple dates efficiently\n- **Resource Management**: Prevents API rate limit issues with controlled processing\n- **Scalable Processing**: Handles large date ranges without blocking requests\n\n## Date Range Processing\n- **Flexible Ranges**: Support for any date range within reasonable limits\n- **Force Refresh Option**: Optional force refresh of existing rates\n- **Incremental Processing**: Processes dates incrementally to manage resources\n- **Error Resilience**: Continues processing even if individual dates fail\n- **Progress Reporting**: Tracks completion status for each date\n\n## Job Management\n- **Queue Integration**: Integrates with background job queue system\n- **Status Tracking**: Provides real-time status updates\n- **Error Handling**: Comprehensive error handling and reporting\n- **Resource Limits**: Respects API quotas and system resources\n- **Completion Notification**: Notifies when job is complete\n\n## Use Cases\n- **Historical Data**: Populate cache with historical exchange rates\n- **System Migration**: Import rates when migrating to new system\n- **Data Backfill**: Fill gaps in exchange rate data\n- **Bulk Updates**: Update rates for extended periods\n- **Compliance**: Ensure complete rate coverage for audit requirements\n\n## Range Limitations\n- **Maximum Range**: Limited to reasonable date ranges to prevent abuse\n- **API Quotas**: Respects external API rate limits and quotas\n- **System Resources**: Balances processing load with system performance\n- **Priority Queuing**: Manages job priority based on date range size\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Start date for range in YYYYMMDD format",
            "example": 20240101,
            "in": "query",
            "name": "startDate",
            "required": true,
            "schema": {
              "maximum": 20991231,
              "minimum": 20000101,
              "type": "integer"
            }
          },
          {
            "description": "End date for range in YYYYMMDD format",
            "example": 20240131,
            "in": "query",
            "name": "endDate",
            "required": true,
            "schema": {
              "maximum": 20991231,
              "minimum": 20000101,
              "type": "integer"
            }
          },
          {
            "description": "Whether to force refresh existing rates",
            "example": false,
            "in": "query",
            "name": "forceRefresh",
            "required": false,
            "schema": {
              "default": false,
              "type": "boolean"
            }
          }
        ],
        "responses": {
          "202": {
            "content": {
              "application/json": {
                "examples": {
                  "job_created": {
                    "summary": "Background job created",
                    "value": {
                      "data": {
                        "created_at": "2024-01-15T10:30:00.000Z",
                        "date_range": {
                          "end_date": 20240131,
                          "start_date": 20240101
                        },
                        "estimated_completion": "2024-01-15T11:00:00.000Z",
                        "force_refresh": false,
                        "job_id": "789e0123-e45b-67c8-d901-234567890123",
                        "processed_days": 0,
                        "status": "queued",
                        "total_days": 31
                      },
                      "message": "Date range fetch job created successfully",
                      "statusCode": 202
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/DateRangeFetchResponse"
                }
              }
            },
            "description": "Date range fetch job created successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Start date must be before or equal to end date",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid date range parameters"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Too many background jobs queued. Please try again later.",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Too many background jobs queued"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Fetch exchange rates for date range (background job)",
        "tags": [
          "Exchange Rates"
        ]
      }
    },
    "/exchange-rates/force-fetch": {
      "post": {
        "description": "Force fetch and update exchange rates from external API, bypassing local cache.\n\n## Force Refresh Strategy\nEnsures fresh data with:\n- **Bypass Cache**: Ignores existing cached rates and fetches fresh data\n- **External API Priority**: Always fetches from external API regardless of cache status\n- **Database Update**: Updates existing rates or creates new ones\n- **Data Freshness**: Guarantees the most current rates available\n- **Override Protection**: Overwrites existing rates with fresh data\n\n## Use Cases\n- **Critical Operations**: Ensure rates are current for important financial transactions\n- **Data Correction**: Refresh rates when external provider has corrected data\n- **System Maintenance**: Update rates as part of system maintenance routines\n- **Audit Requirements**: Ensure rates meet audit requirements for freshness\n- **Real-Time Trading**: Get the most current rates for trading operations\n\n## Force Fetch Process\n1. **API Call**: Direct call to external exchange rate API\n2. **Data Validation**: Validates fetched rates for accuracy\n3. **Database Update**: Updates existing rates or creates new entries\n4. **Cache Refresh**: Refreshes local cache with new data\n5. **Response**: Returns fresh rates with update confirmation\n\n## Provider Reliability\n- **Primary Provider**: Uses configured primary exchange rate provider\n- **Fallback Support**: Falls back to secondary providers if primary fails\n- **Rate Validation**: Validates rates against expected ranges\n- **Error Recovery**: Comprehensive error handling and recovery\n- **API Monitoring**: Monitors API health and performance\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Date for exchange rates in YYYYMMDD format",
            "example": 20240115,
            "in": "query",
            "name": "date",
            "required": true,
            "schema": {
              "maximum": 20991231,
              "minimum": 20000101,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExchangeRateFetchResponse"
                }
              }
            },
            "description": "Exchange rates force fetched successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Date must be a number in YYYYMMDD format",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid date parameter"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          },
          "503": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Exchange rate service temporarily unavailable",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "External API unavailable"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Force fetch fresh exchange rates",
        "tags": [
          "Exchange Rates"
        ]
      }
    },
    "/expense-claims/linked-counts": {
      "get": {
        "description": "\nGet linked document counts for multiple expense claims in a single request.\nUseful for displaying invoice/receipt counts in list views.\n\n**Query Parameters:**\n- `ids`: Comma-separated list of expense claim UUIDs\n\n**Response includes:**\n- Invoice count per claim\n- Receipt count per claim\n- Total linked document count per claim\n      ",
        "operationId": "getLinkedDocumentCounts",
        "parameters": [
          {
            "description": "Comma-separated list of expense claim UUIDs",
            "in": "query",
            "name": "ids",
            "required": true,
            "schema": {
              "example": "uuid-1,uuid-2,uuid-3",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "example": {
                  "data": {
                    "counts": {
                      "uuid-1": {
                        "invoiceCount": 2,
                        "receiptCount": 5,
                        "totalCount": 7
                      },
                      "uuid-2": {
                        "invoiceCount": 0,
                        "receiptCount": 3,
                        "totalCount": 3
                      },
                      "uuid-3": {
                        "invoiceCount": 1,
                        "receiptCount": 0,
                        "totalCount": 1
                      }
                    }
                  },
                  "message": "Linked document counts retrieved successfully",
                  "success": true
                },
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "counts": {
                          "additionalProperties": {
                            "properties": {
                              "invoiceCount": {
                                "example": 2,
                                "type": "integer"
                              },
                              "receiptCount": {
                                "example": 5,
                                "type": "integer"
                              },
                              "totalCount": {
                                "example": 7,
                                "type": "integer"
                              }
                            },
                            "type": "object"
                          },
                          "type": "object"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Linked document counts retrieved successfully",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Linked document counts retrieved successfully"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get linked document counts (batch)",
        "tags": [
          "Expense Claims"
        ]
      }
    },
    "/expense-claims/{id}/available-documents": {
      "get": {
        "description": "\nGet documents that can be linked to an expense claim (not already linked).\n\n**Filters (camelCase, auto-converted):**\n- `type`: Filter by document type ('receipt' or 'invoice')\n- `search`: Search by document name or vendor name\n- `limit`: Max results (default: 50, max: 100)\n- `offset`: Pagination offset\n\n**Returns documents with:**\n- Basic info (id, name, type)\n- Extracted content (amount, vendor, date)\n- Pagination metadata\n      ",
        "operationId": "getAvailableDocuments",
        "parameters": [
          {
            "description": "Expense claim UUID",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Filter by document type",
            "in": "query",
            "name": "type",
            "required": false,
            "schema": {
              "enum": [
                "receipt",
                "invoice"
              ],
              "type": "string"
            }
          },
          {
            "description": "Search term for document name or vendor",
            "in": "query",
            "name": "search",
            "required": false,
            "schema": {
              "maxLength": 100,
              "type": "string"
            }
          },
          {
            "description": "Max results",
            "in": "query",
            "name": "limit",
            "required": false,
            "schema": {
              "default": 50,
              "maximum": 100,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "description": "Pagination offset",
            "in": "query",
            "name": "offset",
            "required": false,
            "schema": {
              "default": 0,
              "minimum": 0,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "documents": {
                          "items": {
                            "properties": {
                              "amount": {
                                "type": "number"
                              },
                              "createdAt": {
                                "format": "date-time",
                                "type": "string"
                              },
                              "documentType": {
                                "type": "string"
                              },
                              "id": {
                                "format": "uuid",
                                "type": "string"
                              },
                              "issueDate": {
                                "type": "integer"
                              },
                              "name": {
                                "type": "string"
                              },
                              "type": {
                                "enum": [
                                  "receipt",
                                  "invoice"
                                ],
                                "type": "string"
                              },
                              "vendorName": {
                                "type": "string"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        },
                        "hasMore": {
                          "type": "boolean"
                        },
                        "limit": {
                          "type": "integer"
                        },
                        "offset": {
                          "type": "integer"
                        },
                        "total": {
                          "type": "integer"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Available documents retrieved successfully"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get available documents for linking",
        "tags": [
          "Expense Claims"
        ]
      }
    },
    "/expense-claims/{id}/link": {
      "post": {
        "description": "\nLink one or more documents (receipts/invoices) to an expense claim.\n\n**Request body (camelCase - auto-converted to snake_case):**\n- `documents`: Array of documents to link\n  - `documentId`: UUID of the document to link\n  - `documentType`: 'receipt' or 'invoice'\n  - `allocatedAmount`: Optional amount to allocate from this document\n  - `category`: Optional category override\n  - `note`: Optional note\n\n**Behavior:**\n- Validates document ownership and type\n- Skips already-linked documents (with warning)\n- Returns partial success if some documents fail\n      ",
        "operationId": "linkDocuments",
        "parameters": [
          {
            "description": "Expense claim UUID",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "example": {
                "documents": [
                  {
                    "allocatedAmount": 5000,
                    "documentId": "550e8400-e29b-41d4-a716-446655440001",
                    "documentType": "receipt"
                  },
                  {
                    "allocatedAmount": 30000,
                    "documentId": "550e8400-e29b-41d4-a716-446655440002",
                    "documentType": "invoice",
                    "note": "オフィス用品購入"
                  }
                ]
              },
              "schema": {
                "properties": {
                  "documents": {
                    "description": "Array of documents to link (send camelCase, auto-converted)",
                    "items": {
                      "properties": {
                        "allocatedAmount": {
                          "description": "Amount to allocate from this document",
                          "type": "number"
                        },
                        "category": {
                          "description": "Category override",
                          "maxLength": 50,
                          "type": "string"
                        },
                        "documentId": {
                          "description": "Document UUID to link",
                          "format": "uuid",
                          "type": "string"
                        },
                        "documentType": {
                          "description": "Type of document",
                          "enum": [
                            "receipt",
                            "invoice"
                          ],
                          "type": "string"
                        },
                        "note": {
                          "description": "Optional note",
                          "maxLength": 500,
                          "type": "string"
                        }
                      },
                      "required": [
                        "documentId",
                        "documentType"
                      ],
                      "type": "object"
                    },
                    "minItems": 1,
                    "type": "array"
                  }
                },
                "required": [
                  "documents"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "linkIds": {
                          "items": {
                            "format": "uuid",
                            "type": "string"
                          },
                          "type": "array"
                        },
                        "linkedCount": {
                          "example": 2,
                          "type": "integer"
                        },
                        "success": {
                          "example": true,
                          "type": "boolean"
                        },
                        "warnings": {
                          "description": "Warnings for skipped documents",
                          "items": {
                            "type": "string"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Successfully linked 2 document(s)",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Documents linked successfully"
          },
          "207": {
            "description": "Partial success - some documents linked with warnings"
          },
          "400": {
            "description": "Invalid request body"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Expense claim not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Link documents to expense claim",
        "tags": [
          "Expense Claims"
        ]
      }
    },
    "/expense-claims/{id}/linked-documents": {
      "get": {
        "description": "\nRetrieve all documents (receipts and invoices) linked to a specific expense claim.\n\n**Response includes (camelCase):**\n- `linkedInvoices`: Array of linked invoice documents\n- `linkedReceipts`: Array of linked receipt documents  \n- `linkedDocumentCount`: Total count of all linked documents\n- `totalAllocatedAmount`: Sum of all allocated amounts\n\n**Each linked document includes:**\n- Document ID, name, type\n- Amount, vendor name, issue date (extracted from document content)\n- Link metadata (linkId, allocatedAmount, category, note, linkedAt)\n      ",
        "operationId": "getLinkedDocuments",
        "parameters": [
          {
            "description": "Expense claim UUID",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Filter by document type",
            "in": "query",
            "name": "type",
            "required": false,
            "schema": {
              "enum": [
                "receipt",
                "invoice"
              ],
              "type": "string"
            }
          },
          {
            "description": "Include full document details (camelCase, auto-converted)",
            "in": "query",
            "name": "includeDetails",
            "required": false,
            "schema": {
              "default": false,
              "type": "boolean"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "example": {
                  "data": {
                    "expenseClaimId": "550e8400-e29b-41d4-a716-446655440000",
                    "expenseClaimName": "2024年3月経費精算",
                    "linkedDocumentCount": 2,
                    "linkedInvoices": [
                      {
                        "allocatedAmount": 30000,
                        "amount": 30000,
                        "category": "invoice",
                        "id": "550e8400-e29b-41d4-a716-446655440001",
                        "issueDate": 20240315,
                        "linkId": "550e8400-e29b-41d4-a716-446655440010",
                        "linkedAt": "2024-03-20T10:00:00Z",
                        "name": "株式会社ABC請求書",
                        "type": "invoice",
                        "vendorName": "株式会社ABC"
                      }
                    ],
                    "linkedReceipts": [
                      {
                        "allocatedAmount": 3500,
                        "amount": 3500,
                        "category": "receipt",
                        "id": "550e8400-e29b-41d4-a716-446655440002",
                        "issueDate": 20240310,
                        "linkId": "550e8400-e29b-41d4-a716-446655440011",
                        "linkedAt": "2024-03-20T10:05:00Z",
                        "name": "タクシー領収書",
                        "type": "receipt",
                        "vendorName": "第一交通"
                      }
                    ],
                    "totalAllocatedAmount": 33500
                  },
                  "message": "Linked documents retrieved successfully",
                  "success": true
                },
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "expenseClaimId": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "expenseClaimName": {
                          "example": "2024年3月経費精算",
                          "type": "string"
                        },
                        "linkedDocumentCount": {
                          "example": 5,
                          "type": "integer"
                        },
                        "linkedInvoices": {
                          "items": {
                            "$ref": "#/components/schemas/LinkedDocument"
                          },
                          "type": "array"
                        },
                        "linkedReceipts": {
                          "items": {
                            "$ref": "#/components/schemas/LinkedDocument"
                          },
                          "type": "array"
                        },
                        "totalAllocatedAmount": {
                          "example": 45000,
                          "type": "number"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Linked documents retrieved successfully"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Expense claim not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get linked documents for expense claim",
        "tags": [
          "Expense Claims"
        ]
      }
    },
    "/expense-claims/{id}/unlink/{document_id}": {
      "delete": {
        "description": "Remove the link between a document and an expense claim.",
        "operationId": "unlinkDocument",
        "parameters": [
          {
            "description": "Expense claim UUID",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Document UUID to unlink (path params use snake_case)",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "success": {
                          "example": true,
                          "type": "boolean"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Document unlinked successfully",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Document unlinked successfully"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Link not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Unlink document from expense claim",
        "tags": [
          "Expense Claims"
        ]
      }
    },
    "/expenses/apply-exchange-rate": {
      "post": {
        "description": "Apply a specific exchange rate to convert a foreign currency expense to Japanese Yen.\n\n## Request Body\n- **expense_id**: UUID of the expense to convert\n- **exchange_rate_id**: UUID of the exchange rate to apply\n\n## Exchange Rate Application\nThis endpoint:\n- Retrieves the specified expense and exchange rate\n- Converts the original amount to Japanese Yen\n- Updates the expense with converted amount\n- Maintains original currency information\n- Links the exchange rate for audit purposes\n\n## Currency Conversion\nThe conversion process:\n- Validates expense and exchange rate exist\n- Applies rate: JPY Amount = Original Amount × Exchange Rate\n- Updates yenAmount field in expense record\n- Preserves original amount and currency\n- Records exchange rate reference\n\n## Use Cases\n- Converting foreign currency receipts\n- Standardizing multi-currency expenses\n- Compliance with Japanese accounting standards\n- Financial reporting in Japanese Yen\n\n## Validation\n- Expense must exist and belong to user\n- Exchange rate must be valid and current\n- Original expense must have amount and currency\n- User must have access to both records\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ApplyExchangeRateRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExchangeRateApplicationResponse"
                }
              }
            },
            "description": "Exchange rate applied successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "INVALID_REQUEST",
                      "type": "string"
                    },
                    "error": {
                      "example": "Expense or exchange rate not found",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid request or missing required data"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Apply exchange rate to expense",
        "tags": [
          "Expenses"
        ]
      }
    },
    "/expenses/bulk-apply-exchange-rate": {
      "post": {
        "description": "Apply a specific exchange rate to multiple foreign currency expenses in a single operation.\n\n## Request Body\n- **expense_ids**: Array of expense UUIDs to convert\n- **exchange_rate_id**: UUID of the exchange rate to apply\n\n## Bulk Processing\nThis endpoint:\n- Processes multiple expenses in parallel\n- Applies the same exchange rate to all expenses\n- Provides aggregated conversion results\n- Maintains individual expense integrity\n- Optimizes performance for large datasets\n\n## Processing Logic\nFor each expense in the array:\n- Validates expense exists and belongs to user\n- Converts original amount to Japanese Yen\n- Updates expense record with converted amount\n- Maintains audit trail and exchange rate reference\n\n## Performance Benefits\n- Reduces API call overhead\n- Parallel processing for efficiency\n- Atomic operation for consistency\n- Batch validation and error handling\n\n## Response Data\nReturns comprehensive results including:\n- Total number of expenses processed\n- Aggregate original and converted amounts\n- Applied exchange rate information\n- Array of successfully processed expense IDs\n\n## Error Handling\n- Continues processing valid expenses if some fail\n- Returns partial results with error details\n- Maintains data consistency throughout\n- Comprehensive error reporting\n\n## Use Cases\n- Bulk currency conversion for monthly reports\n- Processing imported expense data\n- Standardizing multi-currency expense batches\n- Efficient financial data preparation\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/BulkApplyExchangeRateRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BulkExchangeRateApplicationResponse"
                }
              }
            },
            "description": "Bulk exchange rate applied successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "PARTIAL_FAILURE",
                      "type": "string"
                    },
                    "details": {
                      "properties": {
                        "failed": {
                          "example": 2,
                          "type": "integer"
                        },
                        "failed_expenses": {
                          "items": {
                            "type": "string"
                          },
                          "type": "array"
                        },
                        "processed": {
                          "example": 3,
                          "type": "integer"
                        }
                      },
                      "type": "object"
                    },
                    "error": {
                      "example": "Some expenses could not be processed",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid request or some expenses could not be processed"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Apply exchange rate to multiple expenses",
        "tags": [
          "Expenses"
        ]
      }
    },
    "/expenses/document/{document_id}": {
      "get": {
        "description": "Retrieve all expenses associated with a specific document.\n\n## Path Parameters\n- **document_id**: UUID of the document to get expenses for\n\n## Response Data\nReturns array of expenses with complete information including:\n- Expense details (date, vendor, amount, purpose)\n- Japanese tax compliance categorization\n- Payment method and currency information\n- Exchange rate data for foreign currencies\n- Attached receipts and documents\n- Business purpose and remarks\n\n## Expense Categories (Japanese Tax Compliance)\nThe system supports comprehensive Japanese business expense categories:\n- **0**: Entertainment (接待交際費) - External client entertainment\n- **1**: Meeting Expenses (会議費) - Internal meetings, ≤¥5,000/person\n- **2**: Office Supplies (事務用品費) - Office supplies and materials\n- **3**: Travel & Transport (旅費交通費) - Business travel and transportation\n- **4**: Advertising (広告宣伝費) - Marketing and advertising expenses\n- **5**: Utilities (水道光熱費) - Water, electricity, gas\n- **19**: Entertainment Dining (接待飲食費) - Separate tracking for ¥5,000 rule\n- **20**: Welfare Benefits (福利厚生費) - Employee welfare benefits\n- And many more categories for comprehensive compliance\n\n## Tax Types\n- **1**: Taxable 10% (消費税10% - Standard rate)\n- **2**: Taxable 8% (消費税8% - Reduced rate)\n- **3**: Tax Exempt (非課税)\n- **4**: Non-taxable (課税対象外)\n- **5**: Out of scope\n\n## Use Cases\n- Document expense review and analysis\n- Financial reporting and compliance\n- Expense approval workflows\n- Tax preparation and filing\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the document to get expenses for",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExpenseListResponse"
                }
              }
            },
            "description": "Document expenses retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "ACCESS_DENIED",
                      "type": "string"
                    },
                    "error": {
                      "example": "Access denied",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Access denied - document belongs to different user"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get expenses for a document",
        "tags": [
          "Expenses"
        ]
      }
    },
    "/expenses/remove-from-document": {
      "delete": {
        "description": "Remove the association between an expense and a document.\n\n## Query Parameters\n- **expense_id**: UUID of the expense to remove\n- **document_id**: UUID of the document to remove expense from\n\n## Removal Operation\nThis endpoint:\n- Removes the expense-document association\n- Preserves the expense record itself\n- Updates document expense totals\n- Maintains audit trail of the removal\n- Does not delete the actual expense\n\n## Use Cases\n- Correcting expense-document associations\n- Moving expenses between documents\n- Cleaning up incorrect categorizations\n- Document reorganization and management\n\n## Business Logic\nThe removal process:\n- Validates both expense and document exist\n- Verifies user has access to both records\n- Removes the association link\n- Updates any calculated totals\n- Logs the removal for audit purposes\n\n## Impact Assessment\nRemoving an expense from a document affects:\n- Document total amounts and calculations\n- Tax compliance reporting\n- Financial summaries and reports\n- Expense categorization and analysis\n\n## Data Preservation\nImportant notes:\n- The expense record is NOT deleted\n- Only the document association is removed\n- Expense can be re-associated with other documents\n- All expense data and attachments are preserved\n\n## Validation\n- Expense must exist and belong to user\n- Document must exist and belong to user\n- Association must exist between expense and document\n- User must have appropriate permissions\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the expense to remove",
            "in": "query",
            "name": "expense_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "UUID of the document to remove expense from",
            "in": "query",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExpenseRemovalResponse"
                }
              }
            },
            "description": "Expense removed from document successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "ASSOCIATION_NOT_FOUND",
                      "type": "string"
                    },
                    "error": {
                      "example": "Expense-document association not found",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid request or association does not exist"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "ACCESS_DENIED",
                      "type": "string"
                    },
                    "error": {
                      "example": "Access denied",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Access denied - expense or document belongs to different user"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Remove expense from document",
        "tags": [
          "Expenses"
        ]
      }
    },
    "/expenses/{expense_id}": {
      "put": {
        "description": "Update an existing expense with new information.\n\n## Path Parameters\n- **expense_id**: UUID of the expense to update\n\n## Request Body\nAll fields are optional for updates:\n- **expense_date**: Expense date as Unix timestamp\n- **payee**: Vendor or payee name\n- **amount**: Expense amount (must be non-negative)\n- **currency**: Currency code (ISO 4217 format)\n- **category**: Japanese tax compliance category\n- **business_purpose**: Detailed business purpose\n- **remarks**: Array of additional notes and remarks\n- **payment_method**: Payment method used\n- **tax_type**: Japanese tax type classification\n\n## Update Behavior\n- Only provided fields are updated\n- Omitted fields remain unchanged\n- Amount validation ensures non-negative values\n- Category validation ensures tax compliance\n- Currency codes validated against ISO standards\n\n## Japanese Tax Compliance\nThe system enforces proper categorization:\n- Entertainment expenses require proper documentation\n- Meeting expenses have ¥5,000 per person limits\n- Tax types must align with Japanese regulations\n- Business purpose documentation for audit compliance\n\n## Payment Methods\nSupported payment methods include:\n- **0**: Cash (現金)\n- **1**: Credit Card (クレジットカード)\n- **2**: Corporate Card (社用カード)\n- **3**: Debit Card (デビットカード)\n- **4**: Bank Transfer (銀行振込)\n- **5**: IC Card (交通系ICカード)\n- **6**: E-Payment (電子決済)\n- **7**: QR Payment (QRコード決済)\n- **8**: Mobile Payment (モバイル決済)\n- **9**: Company Account (会社口座)\n\n## Validation Rules\n- Expense must exist and belong to user\n- Amount must be non-negative if provided\n- Category must be valid Japanese tax category\n- Currency must be valid ISO 4217 code\n- Tax type must align with Japanese regulations\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the expense to update",
            "in": "path",
            "name": "expense_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateExpenseRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExpenseResponse"
                }
              }
            },
            "description": "Expense updated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "ACCESS_DENIED",
                      "type": "string"
                    },
                    "error": {
                      "example": "Access denied",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Access denied - expense belongs to different user"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update expense",
        "tags": [
          "Expenses"
        ]
      }
    },
    "/file-groups": {
      "get": {
        "description": "Retrieves a paginated list of file groups. Supports filtering by status, group_type, and target_document_type.",
        "parameters": [
          {
            "in": "query",
            "name": "page_number",
            "schema": {
              "default": 1,
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "page_size",
            "schema": {
              "default": 20,
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "status",
            "schema": {
              "enum": [
                "pending",
                "confirmed",
                "archived"
              ],
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "group_type",
            "schema": {
              "enum": [
                "manual",
                "ai_suggested",
                "auto_session"
              ],
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "target_document_type",
            "schema": {
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "sort_by",
            "schema": {
              "default": "created_at",
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "sort_order",
            "schema": {
              "default": "desc",
              "enum": [
                "asc",
                "desc"
              ],
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "items": {
                        "$ref": "#/components/schemas/FileUploadGroup"
                      },
                      "type": "array"
                    },
                    "message": {
                      "type": "string"
                    },
                    "pagination": {
                      "$ref": "#/components/schemas/PaginationMetadata"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Groups retrieved successfully"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List file upload groups",
        "tags": [
          "FileGroup"
        ]
      },
      "post": {
        "description": "Creates a new file group for organizing uploaded files. Groups can be manual, AI-suggested, or auto-created from upload sessions.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateFileGroupRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/FileUploadGroup"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Group created successfully"
          },
          "400": {
            "description": "Validation error"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Source session not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create a file upload group",
        "tags": [
          "FileGroup"
        ]
      }
    },
    "/file-groups/suggest": {
      "post": {
        "description": "Analyzes AI-processed files in an upload session and suggests logical groupings based on category, payee, and document type.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/SuggestGroupingsRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/GroupingSuggestionsResponse"
                }
              }
            },
            "description": "Suggestions generated"
          },
          "404": {
            "description": "Session not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "AI-suggest groupings from session files",
        "tags": [
          "FileGroup"
        ]
      }
    },
    "/file-groups/{id}": {
      "delete": {
        "description": "Deletes a group and unlinks all files (files are NOT deleted). Cannot be undone.",
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Group deleted successfully"
          },
          "404": {
            "description": "Group not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Delete a file group",
        "tags": [
          "FileGroup"
        ]
      },
      "get": {
        "description": "Retrieves a file group with all its files, document link, and session info in a single consolidated response.",
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FileGroupFullResponse"
                }
              }
            },
            "description": "Group retrieved successfully"
          },
          "404": {
            "description": "Group not found or access denied"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get group with all files and document link",
        "tags": [
          "FileGroup"
        ]
      },
      "patch": {
        "description": "Updates group label, description, or target document type. Cannot update confirmed groups.",
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateFileGroupRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/FileUploadGroup"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Group updated successfully"
          },
          "400": {
            "description": "Cannot update confirmed group"
          },
          "404": {
            "description": "Group not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update a file group",
        "tags": [
          "FileGroup"
        ]
      }
    },
    "/file-groups/{id}/confirm": {
      "post": {
        "description": "Links all files in the group to the specified document via file_document_links and marks the group as confirmed. Requires a document_id in the request or already set on the group.",
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ConfirmFileGroupRequest"
              }
            }
          },
          "required": false
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ConfirmGroupResponse"
                }
              }
            },
            "description": "Group confirmed and files linked to document"
          },
          "400": {
            "description": "Empty group, no document_id available, or validation error"
          },
          "404": {
            "description": "Group or document not found"
          },
          "409": {
            "description": "Group already confirmed"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Confirm group and link files to document",
        "tags": [
          "FileGroup"
        ]
      }
    },
    "/file-groups/{id}/files": {
      "post": {
        "description": "Assigns file_uploads to this group by setting group_id. Files already in another group are rejected.",
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AddFilesToGroupRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/FileUploadGroup"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Files added successfully"
          },
          "400": {
            "description": "Cannot modify confirmed group"
          },
          "404": {
            "description": "Group or files not found"
          },
          "409": {
            "description": "Files already in another group"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Add files to group",
        "tags": [
          "FileGroup"
        ]
      }
    },
    "/file-groups/{id}/files/{file_id}": {
      "delete": {
        "description": "Removes a file from the group (sets group_id to null). Does not delete the file.",
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "in": "path",
            "name": "file_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "File removed from group"
          },
          "400": {
            "description": "Cannot modify confirmed group"
          },
          "404": {
            "description": "File not found in group"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Remove file from group",
        "tags": [
          "FileGroup"
        ]
      }
    },
    "/file-upload": {
      "get": {
        "description": "Retrieve all file upload records for the authenticated user with complete metadata.\n\n## File Listing\nReturns comprehensive list of user files:\n- **Complete Records**: All file information including metadata\n- **Processing Status**: Current status of each file in workflow\n- **Organization**: Folder assignments and file categorization\n- **AI Data**: Extracted information and analysis results\n- **Storage Information**: URLs and access details\n\n## File Information Included\n- **Basic Details**: Names, types, sizes, and upload dates\n- **Storage URLs**: Direct access links to Supabase storage\n- **Processing Data**: AI analysis results and user confirmations\n- **Organization**: Folder assignments and categorization\n- **Metadata**: Technical details and processing information\n\n## Sorting and Organization\n- **Chronological**: Most recent uploads first\n- **Type Grouping**: Files organized by type (image, PDF, DOCX)\n- **Status Filtering**: Processing status and workflow stage\n- **Folder Organization**: Hierarchical folder structure\n\n## Use Cases\n- **File Management**: Display user's complete file library\n- **Dashboard Views**: Show recent uploads and processing status\n- **Organization**: File browser and folder management interfaces\n- **Analytics**: File usage and storage analysis\n- **Search**: File discovery and content management\n\n## Performance Considerations\n- **Pagination**: Large file collections may require pagination\n- **Metadata Loading**: Rich metadata included in response\n- **Image Thumbnails**: URLs provided for image preview\n- **Caching**: Response suitable for client-side caching\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FileListResponse"
                }
              }
            },
            "description": "Files retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get all user files",
        "tags": [
          "File Upload"
        ]
      },
      "post": {
        "description": "Create a new file upload record in the database with metadata and storage information.\n\n## File Upload Record Creation\nCreates database record for uploaded files with:\n- **File Information**: Name, URL, type, and metadata\n- **Storage Details**: Supabase bucket and path information\n- **Processing Status**: Initial status and workflow tracking\n- **AI Integration**: Optional AI data and confirmed data storage\n- **Organization**: Optional folder assignment for file organization\n\n## File Types Supported\n- **Image**: JPEG, PNG files for receipts and documents\n- **PDF**: PDF documents for invoices and contracts\n- **DOCX**: Word documents for text-based content\n\n## Processing Workflow\n- **Storage**: Initial upload to Supabase storage\n- **Processed**: AI analysis and data extraction completed\n- **Settlement**: User confirmation and data validation\n- **Organization**: Folder assignment and categorization\n\n## Metadata Management\nComprehensive file metadata storage:\n- **Original Information**: Filename and upload details\n- **Storage Information**: Bucket, path, and sanitized names\n- **File Properties**: Size, type, and technical metadata\n- **Processing Data**: AI analysis results and user confirmations\n\n## Use Cases\n- **Manual File Registration**: Register files uploaded directly to storage\n- **Batch Processing**: Create records for bulk uploaded files\n- **Integration**: Third-party system file registration\n- **Migration**: Import existing file records into system\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "basic_image_upload": {
                  "summary": "Basic image file upload record",
                  "value": {
                    "bucket": "invoices",
                    "file_name": "receipt_restaurant_2024.jpg",
                    "file_type": "image",
                    "file_url": "https://supabase.co/storage/v1/object/public/invoices/user123/receipt_20240115.jpg",
                    "status": "storage"
                  }
                },
                "complete_with_metadata": {
                  "summary": "Complete upload record with metadata",
                  "value": {
                    "ai_data": {
                      "amount": 5000,
                      "confidence": 0.92,
                      "extractedText": "Invoice #INV-2024-001...",
                      "vendor": "ABC Corporation"
                    },
                    "bucket": "invoices",
                    "file_metadata": {
                      "bucketName": "invoices",
                      "filePath": "user123/business_invoice_2024_01_1705312200000.pdf",
                      "fileSize": 2048576,
                      "originalFileName": "business_invoice_2024_01.pdf",
                      "sanitizedFileName": "business_invoice_2024_01_1705312200000.pdf"
                    },
                    "file_name": "business_invoice_2024_01.pdf",
                    "file_type": "pdf",
                    "file_url": "https://supabase.co/storage/v1/object/public/invoices/user123/invoice_20240115.pdf",
                    "folder_id": "456e7890-f12a-34b5-c678-901234567890"
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/CreateFileUploadRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FileUploadResponse"
                }
              }
            },
            "description": "File upload record created successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Invalid file type or missing required fields",
                      "type": "string"
                    },
                    "fieldErrors": {
                      "additionalProperties": {
                        "items": {
                          "type": "string"
                        },
                        "type": "array"
                      },
                      "example": {
                        "file_type": [
                          "file_type must be one of: image, pdf, docx"
                        ]
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid request data or validation errors"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create file upload record",
        "tags": [
          "File Upload"
        ]
      }
    },
    "/file-upload/bulk": {
      "delete": {
        "description": "Delete multiple files simultaneously with automatic storage and database cleanup.\n\n## Bulk Deletion Specifications\n- **Multiple Files**: Delete several files in a single operation\n- **Batch Processing**: Efficient bulk deletion operations\n- **Partial Success**: Some files can be deleted while others fail\n- **Atomic Records**: Each file deletion is independent\n- **Comprehensive Cleanup**: Storage and database removal for each file\n\n## Deletion Workflow\n1. **Validation**: Verify file IDs and user permissions\n2. **Ownership Check**: Ensure user owns all specified files\n3. **Database Removal**: Delete file records from database\n4. **Storage Cleanup**: Remove files from Supabase storage\n5. **Relationship Cleanup**: Clear file associations and references\n6. **Response**: Detailed results with success/failure breakdown\n\n## Batch Processing Benefits\n- **Efficiency**: Delete multiple files in single request\n- **Performance**: Optimized database and storage operations\n- **Flexibility**: Partial success handling for failed deletions\n- **User Experience**: Simplified file management workflow\n- **Transaction Safety**: Independent file deletions prevent cascade failures\n\n## Use Cases\n- **Bulk Cleanup**: Remove multiple unwanted files at once\n- **Storage Management**: Free up storage space efficiently\n- **Batch Operations**: Delete files from completed projects\n- **Error Correction**: Remove multiple incorrect uploads\n- **Archive Operations**: Clean up old or expired files\n- **Privacy Compliance**: Bulk removal of sensitive data\n\n## Deletion Results\nReturns comprehensive batch deletion results:\n- **Success List**: Successfully deleted files with details\n- **Failure List**: Failed deletions with specific error information\n- **Statistics**: Count of successful and failed deletions\n- **Individual Results**: Detailed information for each file\n\n## Error Handling\n- **Individual Failures**: Some files can fail while others succeed\n- **Detailed Errors**: Specific error messages for each failure\n- **Partial Success**: Batch succeeds even if some files fail\n- **Permission Errors**: Clear messages for access denied cases\n- **Not Found Handling**: Identify non-existent or already deleted files\n\n## Safety Considerations\n- **Ownership Verification**: All files must belong to authenticated user\n- **Permission Checks**: Verify deletion rights for each file\n- **Audit Logging**: Record bulk deletion operations for compliance\n- **Recovery Information**: Deletion details for backup recovery\n- **Validation**: Comprehensive checks before deletion\n\n## Storage Cleanup\n- **File Removal**: Delete files from Supabase storage\n- **Database Records**: Remove all associated database entries\n- **Metadata Cleanup**: Clear AI data and processing information\n- **Cache Invalidation**: Remove cached data and thumbnails\n- **Statistics Update**: Recalculate file statistics and usage metrics\n\n## Authentication\nRequires valid Bearer token in Authorization header.\n\n## 仕訳の証憑 (je_link, BE ADR-0008)\nA file linked to a 仕訳 with `POST /file-uploads/{file_id}/link` (type `je_link`) is\nconsumption-tax evidence, so deleting it moves the credit exactly as an unlink does:\n- **423 PERIOD_LOCKED** when any linked 仕訳 falls in a filed / closed / audited\n  period, or in a 課税期間 with a filed return. Nothing is deleted.\n- Otherwise the links are deleted with the file, in one transaction, and\n  `meta.removedEvidenceLinks` in the 200 envelope counts them, so the client can\n  tell the user which evidence went.",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "delete_multiple_files": {
                  "summary": "Delete multiple files",
                  "value": {
                    "file_ids": [
                      "123e4567-e89b-12d3-a456-426614174000",
                      "789e0123-e45b-67c8-d901-234567890123",
                      "abc12345-def6-7890-ghij-klmnopqrstuv"
                    ]
                  }
                },
                "delete_single_in_bulk": {
                  "summary": "Delete single file using bulk endpoint",
                  "value": {
                    "file_ids": [
                      "123e4567-e89b-12d3-a456-426614174000"
                    ]
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/DeleteFilesRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BulkDeleteResponse"
                }
              }
            },
            "description": "Bulk deletion completed (may include partial failures)"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "No file IDs provided or invalid format",
                      "type": "string"
                    },
                    "fieldErrors": {
                      "additionalProperties": {
                        "items": {
                          "type": "string"
                        },
                        "type": "array"
                      },
                      "example": {
                        "file_ids": [
                          "At least one file ID must be provided",
                          "All file IDs must be valid UUIDs"
                        ]
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid request data or validation errors"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Access denied to one or more files",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Access denied - one or more files belong to different user"
          },
          "423": {
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetails"
                }
              }
            },
            "description": "A file is 証憑 on a 仕訳 in a filed / closed period (PERIOD_LOCKED); nothing was deleted"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Bulk delete files",
        "tags": [
          "File Upload"
        ]
      }
    },
    "/file-upload/bulk-upload": {
      "post": {
        "description": "Upload multiple files simultaneously with automatic storage and database record creation.\n\n## Bulk Upload Specifications\n- **Maximum Files**: 10 files per batch upload\n- **File Size Limit**: 2MB per individual file\n- **Supported Types**: JPEG, PNG, PDF, DOCX (validated by MIME type)\n- **Processing**: Automatic storage and database record creation\n- **Organization**: Optional folder assignment for all files\n\n## File Processing Workflow\n1. **Validation**: File type and size validation\n2. **Sanitization**: Filename cleaning for storage compatibility\n3. **Storage**: Upload to Supabase with user-specific paths\n4. **Database**: Create individual records for each file\n5. **Organization**: Optional folder assignment\n6. **Response**: Detailed results with success/failure breakdown\n\n## Supported File Types\n- **Images**: JPEG, PNG for receipts and document scanning\n- **Documents**: PDF, DOCX for text-based content processing\n- **Validation**: MIME type validation prevents invalid uploads\n- **Security**: File content validation and sanitization\n\n## Storage Organization\n- **User Paths**: Files stored in user-specific directories\n- **Sanitization**: Filenames cleaned for storage compatibility\n- **Timestamps**: Unique timestamps prevent filename conflicts\n- **Metadata**: Complete storage metadata preserved\n\n## Batch Results\nReturns comprehensive batch processing results:\n- **Success List**: Successfully uploaded files with database records\n- **Failure List**: Failed files with detailed error information\n- **Statistics**: Count of successful and failed uploads\n- **Individual Records**: Complete file information for each success\n\n## Error Handling\n- **Individual Failures**: Some files can fail while others succeed\n- **Detailed Errors**: Specific error messages for each failure\n- **Partial Success**: Batch succeeds even if some files fail\n- **Recovery Information**: Details for retry or correction\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "multipart/form-data": {
              "schema": {
                "properties": {
                  "files": {
                    "description": "Array of files to upload (max 10 files, 2MB each)",
                    "items": {
                      "format": "binary",
                      "type": "string"
                    },
                    "maxItems": 10,
                    "type": "array"
                  },
                  "folder_id": {
                    "description": "Optional folder ID for file organization",
                    "example": "456e7890-f12a-34b5-c678-901234567890",
                    "format": "uuid",
                    "type": "string"
                  }
                },
                "required": [
                  "files"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BulkUploadResponse"
                }
              }
            },
            "description": "Bulk upload completed (may include partial failures)"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "details": {
                      "items": {
                        "properties": {
                          "error": {
                            "example": "Unsupported file type",
                            "type": "string"
                          },
                          "fileName": {
                            "example": "document.txt",
                            "type": "string"
                          }
                        },
                        "type": "object"
                      },
                      "type": "array"
                    },
                    "error": {
                      "example": "No files provided or invalid file types",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid files or validation errors"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "413": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "File size limit exceeded (2MB max per file) or too many files (10 max)",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "File size or count limit exceeded"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Bulk file upload with storage",
        "tags": [
          "File Upload"
        ]
      }
    },
    "/file-upload/move-to-folder": {
      "put": {
        "description": "Move multiple files to a specified folder for organization and categorization.\n\n## File Organization\nBatch operation to organize files into folders:\n- **Multiple Files**: Move several files simultaneously\n- **Folder Assignment**: Assign files to existing folder structure\n- **Batch Processing**: Efficient bulk organization operations\n- **Atomic Operation**: All files moved together or operation fails\n- **Organization Tracking**: Update file records with folder assignments\n\n## Folder Structure Integration\n- **Hierarchical Organization**: Support for nested folder structures\n- **Folder Validation**: Ensure target folder exists and is accessible\n- **User Permissions**: Verify user owns both files and target folder\n- **Relationship Management**: Maintain file-folder relationships in database\n\n## Batch Operation Benefits\n- **Efficiency**: Move multiple files in single operation\n- **Consistency**: Ensure all files moved to same location\n- **Transaction Safety**: Atomic operation prevents partial moves\n- **Performance**: Optimized database operations for bulk updates\n- **User Experience**: Simplified organization workflow\n\n## Use Cases\n- **File Organization**: Organize uploaded files into project folders\n- **Batch Categorization**: Group related files together\n- **Workflow Management**: Move files through processing stages\n- **Archive Operations**: Organize completed files into archive folders\n- **Project Management**: Group files by project or category\n\n## Validation Requirements\n- **File Ownership**: User must own all specified files\n- **Folder Access**: User must have access to target folder\n- **File Existence**: All specified files must exist and not be deleted\n- **Folder Capacity**: Target folder must support additional files\n- **Permission Checks**: Verify move permissions for all files\n\n## Operation Results\n- **Move Count**: Number of files successfully moved\n- **Folder Information**: Target folder details and confirmation\n- **Error Handling**: Detailed error information for any failures\n- **Status Updates**: Updated file records with new folder assignments\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "move_receipts": {
                  "summary": "Move receipt files to receipts folder",
                  "value": {
                    "file_ids": [
                      "123e4567-e89b-12d3-a456-426614174000",
                      "789e0123-e45b-67c8-d901-234567890123",
                      "abc12345-def6-7890-ghij-klmnopqrstuv"
                    ],
                    "folder_id": "456e7890-f12a-34b5-c678-901234567890"
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/MoveFilesToFolderRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FileMoveResponse"
                }
              }
            },
            "description": "Files moved to folder successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Invalid file IDs or folder ID format",
                      "type": "string"
                    },
                    "fieldErrors": {
                      "additionalProperties": {
                        "items": {
                          "type": "string"
                        },
                        "type": "array"
                      },
                      "example": {
                        "file_ids": [
                          "At least one file ID must be provided"
                        ],
                        "folder_id": [
                          "Folder ID must be a valid UUID"
                        ]
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid request or validation errors"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Access denied to files or target folder",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Access denied - files or folder belong to different user"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "One or more files or target folder not found",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Files or folder not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Move files to folder",
        "tags": [
          "File Upload"
        ]
      }
    },
    "/file-upload/stats": {
      "get": {
        "description": "Retrieve comprehensive file statistics and usage metrics for the authenticated user.\n\n## Statistics Overview\nReturns detailed analytics about user's file collection:\n- **File Counts**: Total files and breakdown by type and status\n- **Storage Usage**: Total storage consumed in bytes\n- **Processing Status**: Files by processing stage\n- **Organization Metrics**: File distribution and categorization\n- **Workflow Analytics**: Unsettled files and processing pipeline\n\n## File Type Analytics\n- **Image Files**: Count of uploaded images (JPEG, PNG)\n- **PDF Documents**: Count of PDF files for invoices and contracts\n- **DOCX Documents**: Count of Word documents and text files\n- **Type Distribution**: Percentage breakdown of file types\n\n## Processing Status Metrics\n- **Storage Files**: Files uploaded but not yet processed\n- **Processed Files**: Files with completed AI analysis\n- **Pending Files**: Files awaiting user confirmation\n- **Error Files**: Files with processing failures\n\n## Storage Analytics\n- **Total Usage**: Cumulative storage consumption\n- **Average File Size**: Mean file size across collection\n- **Storage Efficiency**: Compression and optimization metrics\n- **Growth Trends**: Storage usage over time\n\n## Workflow Metrics\n- **Unsettled Count**: Files requiring user attention\n- **Processing Queue**: Files awaiting AI analysis\n- **Completion Rate**: Percentage of fully processed files\n- **Error Rate**: Percentage of files with processing issues\n\n## Use Cases\n- **Dashboard Widgets**: Display key metrics in user interface\n- **Storage Management**: Monitor storage usage and limits\n- **Processing Analytics**: Track file processing efficiency\n- **User Insights**: Understand user file management patterns\n- **System Monitoring**: Track overall system usage and performance\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FileStatisticsResponse"
                }
              }
            },
            "description": "File statistics retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get file statistics",
        "tags": [
          "File Upload"
        ]
      }
    },
    "/file-upload/unsettled": {
      "get": {
        "description": "Retrieve files that require user attention or further processing.\n\n## Unsettled File Criteria\nFiles are considered unsettled when they:\n- **Need Processing**: Recently uploaded but not yet AI processed\n- **Require Confirmation**: AI analysis completed but user confirmation pending\n- **Have Errors**: Processing failed and require user intervention\n- **Missing Data**: Incomplete information requiring user input\n- **Pending Organization**: Files not yet assigned to folders or categories\n\n## Processing Workflow\nUnsettled files represent different stages:\n- **Storage Stage**: Uploaded to storage but not processed\n- **Analysis Stage**: AI processing in progress or failed\n- **Confirmation Stage**: Awaiting user review and confirmation\n- **Organization Stage**: Requiring folder assignment or categorization\n\n## Use Cases\n- **User Dashboards**: Show files requiring attention\n- **Processing Queues**: Display files awaiting processing\n- **Review Workflows**: Files needing user confirmation\n- **Error Handling**: Files with processing issues\n- **Onboarding**: Help users complete file setup\n\n## File Information\nReturns same detailed information as main file listing:\n- **Processing Status**: Current stage in workflow\n- **Error Information**: Details about processing failures\n- **AI Results**: Analysis results requiring confirmation\n- **Suggested Actions**: Next steps for file completion\n\n## Workflow Integration\n- **Notification Systems**: Alert users to unsettled files\n- **Processing Dashboards**: Show pending work items\n- **Batch Operations**: Process multiple unsettled files\n- **Quality Assurance**: Review and validate file processing\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FileListResponse"
                }
              }
            },
            "description": "Unsettled files retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get unsettled files",
        "tags": [
          "File Upload"
        ]
      }
    },
    "/file-upload/{file_id}": {
      "delete": {
        "description": "Delete a specific file from both storage and database with comprehensive cleanup.\n\n## File Deletion Process\nComprehensive file removal operation:\n- **Database Removal**: Delete file record from database\n- **Storage Cleanup**: Remove file from Supabase storage\n- **Relationship Cleanup**: Remove file associations and references\n- **Metadata Cleanup**: Clear AI data and processing information\n- **Audit Trail**: Maintain deletion logs for compliance\n\n## Deletion Scope\n- **File Record**: Complete database record removal\n- **Storage File**: Physical file deletion from Supabase\n- **Metadata**: AI analysis data and user confirmations\n- **Relationships**: Folder associations and references\n- **Processing Data**: Queue entries and processing history\n\n## Safety Measures\n- **Ownership Verification**: Ensure user owns the file before deletion\n- **Soft Delete Option**: Mark as deleted without physical removal (configurable)\n- **Backup Considerations**: Integration with backup and recovery systems\n- **Audit Logging**: Record deletion operations for compliance\n- **Permission Checks**: Verify deletion permissions and access rights\n\n## Use Cases\n- **File Management**: Remove unwanted or duplicate files\n- **Storage Cleanup**: Free storage space and optimize usage\n- **Privacy Compliance**: Remove files containing sensitive data\n- **Error Correction**: Delete files uploaded in error\n- **Workflow Management**: Remove files from processing pipelines\n\n## Cleanup Operations\n- **Storage Reclamation**: Free allocated storage space\n- **Database Optimization**: Remove unused records and references\n- **Cache Invalidation**: Clear cached file data and thumbnails\n- **Search Index**: Remove file from search and discovery systems\n- **Analytics Update**: Update file statistics and usage metrics\n\n## Recovery Considerations\n- **Backup Systems**: Files may be recoverable from backups\n- **Soft Delete**: Option to mark as deleted without physical removal\n- **Audit Trail**: Deletion operations logged for recovery assistance\n- **Version Control**: Previous versions may remain in version history\n\n## Authentication\nRequires valid Bearer token in Authorization header.\n\n## 仕訳の証憑 (je_link, BE ADR-0008)\nA file linked to a 仕訳 with `POST /file-uploads/{file_id}/link` (type `je_link`) is\nconsumption-tax evidence, so deleting it moves the credit exactly as an unlink does:\n- **423 PERIOD_LOCKED** when any linked 仕訳 falls in a filed / closed / audited\n  period, or in a 課税期間 with a filed return. Nothing is deleted.\n- Otherwise the links are deleted with the file, in one transaction, and\n  `meta.removedEvidenceLinks` in the 200 envelope counts them, so the client can\n  tell the user which evidence went.",
        "parameters": [
          {
            "description": "UUID of the file to delete",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "in": "path",
            "name": "file_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FileDeleteResponse"
                }
              }
            },
            "description": "File deleted successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Invalid file ID format",
                      "type": "string"
                    },
                    "fieldErrors": {
                      "properties": {
                        "file_id": {
                          "example": [
                            "Invalid ID format"
                          ],
                          "items": {
                            "type": "string"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid file ID format"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Access denied - insufficient permissions to delete this file",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Access denied - file belongs to different user"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "File not found or already deleted",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "File not found"
          },
          "423": {
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetails"
                }
              }
            },
            "description": "A file is 証憑 on a 仕訳 in a filed / closed period (PERIOD_LOCKED); nothing was deleted"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Delete file",
        "tags": [
          "File Upload"
        ]
      }
    },
    "/file-uploads/search": {
      "get": {
        "description": "Relevance-ranked search across the caller's uploaded files.\n\n## Retrieval\nTwo legs fused with Reciprocal Rank Fusion:\n- **Lexical** — PGroonga full-text over a denormalized `search_text` (filename,\n  counterparty, doc class, OCR fields, promoted agreement terms), NFKC-normalized\n  and particle-stripped so 「オフィスの賃貸借」 still matches 事業用賃貸借契約書.\n- **Semantic** — `text-embedding-3-small` (1536-d) cosine over the same corpus,\n  gated at a minimum similarity so an unrelated query returns nothing rather than\n  its nearest neighbour.\n\n`mode` reports which path answered: `hybrid` (both legs), `lexical` (embedding\nunavailable — degraded but still useful), `structured` (filters only, no `q`),\nor `empty`.\n\n## Not paginated\nRRF ranks are unstable across offsets, so this returns a bounded top-K by\nrelevance. `limit` is the entire budget; there is no page cursor.\n\n## Authentication\nRequires a valid Bearer token. Results are always scoped to the caller.",
        "parameters": [
          {
            "description": "Free-text query. Omit for a filter-only listing.",
            "example": "オフィスの賃貸借契約",
            "in": "query",
            "name": "q",
            "required": false,
            "schema": {
              "maxLength": 200,
              "minLength": 1,
              "type": "string"
            }
          },
          {
            "example": "lease",
            "in": "query",
            "name": "doc_class",
            "required": false,
            "schema": {
              "maxLength": 64,
              "type": "string"
            }
          },
          {
            "example": "干俣牧場組合",
            "in": "query",
            "name": "counterparty",
            "required": false,
            "schema": {
              "maxLength": 200,
              "minLength": 1,
              "type": "string"
            }
          },
          {
            "description": "Inclusive lower bound on transaction_date (YYYY-MM-DD).",
            "in": "query",
            "name": "date_from",
            "required": false,
            "schema": {
              "format": "date",
              "type": "string"
            }
          },
          {
            "description": "Inclusive upper bound on transaction_date (YYYY-MM-DD).",
            "in": "query",
            "name": "date_to",
            "required": false,
            "schema": {
              "format": "date",
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "limit",
            "required": false,
            "schema": {
              "default": 20,
              "maximum": 40,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "count": {
                          "example": 3,
                          "type": "integer"
                        },
                        "items": {
                          "items": {
                            "$ref": "#/components/schemas/FileSearchHit"
                          },
                          "type": "array"
                        },
                        "mode": {
                          "enum": [
                            "hybrid",
                            "lexical",
                            "structured",
                            "empty"
                          ],
                          "example": "hybrid",
                          "type": "string"
                        },
                        "query": {
                          "description": "Normalized query actually sent to the lexical leg.",
                          "example": "オフィス 賃貸借契約",
                          "nullable": true,
                          "type": "string"
                        }
                      },
                      "required": [
                        "items",
                        "count",
                        "mode"
                      ],
                      "type": "object"
                    },
                    "message": {
                      "example": "File search completed",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "message",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Ranked matches (possibly empty)"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Hybrid search over uploaded evidence",
        "tags": [
          "File Upload"
        ]
      }
    },
    "/file-uploads/{file_id}/analyze": {
      "post": {
        "description": "Reads the file with the parse ladder and streams progress as Server-Sent Events:\n`starting → downloading → parsing → persisting → done | error`. The final `done` frame carries\n`result` (fileId, analysisStatus, engine, qualityScore, isDuplicate, verdict, extractedFields).\n\nA read with quality ≥ 0.65 is cached in `document_parse_results` and replayed on the next call\nwith no token spend. `bypass_parse_cache: true` skips that cache and reads the document again —\nfor a read made under an older prompt or schema. It costs tokens on every call.\n\nA file that is already classified and has `confirmed_data` is never re-read here, with or\nwithout the flag: the stream ends with `result.engine = \"confirmed_data_preserved\"` and\n`result.verdict.preservedConfirmedData = true`. Overriding a human's confirmed read is not\nexposed on this endpoint.\n\nUnknown body keys are a 400 (sent before the stream opens).",
        "parameters": [
          {
            "in": "path",
            "name": "file_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "additionalProperties": false,
                "properties": {
                  "bypass_parse_cache": {
                    "description": "Skip the document_parse_results cache and read the document again. Does not override confirmed_data.",
                    "type": "boolean"
                  },
                  "mode": {
                    "description": "'auto' (default), 'compare', or a specific parse engine name",
                    "maxLength": 64,
                    "type": "string"
                  },
                  "purpose": {
                    "description": "expense | invoice | receipt | contract | payslip | subsidy | tax_notice | general (default)",
                    "maxLength": 32,
                    "type": "string"
                  }
                },
                "type": "object"
              }
            }
          },
          "required": false
        },
        "responses": {
          "200": {
            "content": {
              "text/event-stream": {
                "schema": {
                  "example": "data: {\"stage\":\"done\",\"result\":{\"fileId\":\"…\",\"analysisStatus\":\"completed\",\"engine\":\"confirmed_data_preserved\",\"qualityScore\":1}}\n\n",
                  "type": "string"
                }
              }
            },
            "description": "SSE stream of progress frames, ending with a done (or error) frame"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Run the parse ladder on one file (SSE progress)",
        "tags": [
          "File Upload"
        ]
      }
    },
    "/file-uploads/{file_id}/link": {
      "post": {
        "description": "Writes a reversible link and an `audit_logs` row (`file_linked`, revertable).\n\n| type | target_id | writes |\n|---|---|---|\n| `expense_link` | 経費 id | `expenses.upload_id` |\n| `document_link` | 書類 id | `file_document_links` |\n| `tx_link` | 取引明細 id | `bank_transaction_evidence` |\n| `je_link` | 仕訳 id | `journal_entry_evidence` (BE ADR-0008) |\n\n## je_link\nA 証憑 on a journal entry that has no bank row (an accrual, a 前渡金 → 支払手数料 振替).\n`target_id` must be the 仕訳's UUID (400 otherwise).\nIt counts as consumption-tax evidence per line: with `line_id` for that line only;\nwithout it (JE-level) only when the entry has exactly one debit line. A JE-level link\non a multi-vendor entry is recorded but not counted, and the drill tells the user to\nattach it to its line. `line_id`, `link_type` and `note` are accepted only for je_link.\n\n`link_type` (default `invoice`): `invoice` and `receipt` count as evidence;\n`attachment` (a quote, a contract, a memo) is kept but never counts. A contract that\nIS the 適格請求書 (rent: contract + transfer record) is linked as `invoice` on purpose.\nLinking the same file to the same scope again with another `link_type` changes it.\n\nBecause it moves the credit, je_link is refused with **423** when the entry falls in a\nfiled / closed / audited fiscal period, or in a 課税期間 that has a filed return.",
        "parameters": [
          {
            "in": "path",
            "name": "file_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "line_id": {
                    "description": "je_link only: attach to this 仕訳 line instead of the whole entry.",
                    "format": "uuid",
                    "type": "string"
                  },
                  "link_type": {
                    "description": "je_link only (default invoice). invoice / receipt count as 消費税 evidence; attachment never does. A re-link of the same scope changes it.",
                    "enum": [
                      "invoice",
                      "receipt",
                      "attachment"
                    ],
                    "type": "string"
                  },
                  "note": {
                    "description": "je_link only.",
                    "maxLength": 500,
                    "type": "string"
                  },
                  "proposal_id": {
                    "maxLength": 200,
                    "type": "string"
                  },
                  "target_id": {
                    "description": "The 経費 / 書類 / 取引明細 / 仕訳 id. For je_link it must be the 仕訳 UUID (400 otherwise).",
                    "example": "cdd72218-1545-4e25-8cf7-9c785ce4b2de",
                    "maxLength": 64,
                    "minLength": 1,
                    "type": "string"
                  },
                  "type": {
                    "enum": [
                      "expense_link",
                      "document_link",
                      "tx_link",
                      "je_link"
                    ],
                    "type": "string"
                  }
                },
                "required": [
                  "type",
                  "target_id"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "linkId": {
                          "type": "string"
                        },
                        "linked": {
                          "example": true,
                          "type": "boolean"
                        },
                        "undoToken": {
                          "type": "string"
                        }
                      },
                      "required": [
                        "linked",
                        "undoToken"
                      ],
                      "type": "object"
                    },
                    "message": {
                      "example": "ファイルを連携しました",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "message",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Linked (a repeat link of the same scope returns the existing row, with its link_type updated)"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "423": {
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetails"
                }
              }
            },
            "description": "je_link or tx_link on a filed / closed period (PERIOD_LOCKED, BE ADR-0008 / ADR-0011)"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Link an uploaded 証憑 file to a 経費 / 書類 / 取引明細 / 仕訳",
        "tags": [
          "File Upload"
        ]
      }
    },
    "/file-uploads/{file_id}/links": {
      "delete": {
        "description": "Removes one 書類 / 取引明細 / 仕訳 link and writes an `audit_logs` row (`file_unlinked`).\nFor je_link, `line_id` selects the line-scoped link (omit it for the JE-level one), and the\nsame 423 period guard as the link applies: removing evidence moves the credit too.",
        "parameters": [
          {
            "in": "path",
            "name": "file_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "line_id": {
                    "description": "je_link only.",
                    "format": "uuid",
                    "type": "string"
                  },
                  "target_id": {
                    "maxLength": 64,
                    "minLength": 1,
                    "type": "string"
                  },
                  "type": {
                    "enum": [
                      "document_link",
                      "tx_link",
                      "je_link"
                    ],
                    "type": "string"
                  }
                },
                "required": [
                  "type",
                  "target_id"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "unlinked": {
                          "example": true,
                          "type": "boolean"
                        }
                      },
                      "required": [
                        "unlinked"
                      ],
                      "type": "object"
                    },
                    "message": {
                      "example": "連携を解除しました",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "message",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Unlinked, or no such link"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "423": {
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetails"
                }
              }
            },
            "description": "je_link or tx_link on a filed / closed period (PERIOD_LOCKED, BE ADR-0008 / ADR-0011)"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Detach one existing link of an uploaded file",
        "tags": [
          "File Upload"
        ]
      }
    },
    "/file-uploads/{file_id}/split": {
      "post": {
        "description": "Cuts a multi-page PDF (a phone scan holding several 領収証 / 請求書) into one child\n`file_uploads` row per page so each page can be analysed and linked on its own. Each child\ngoes through the normal upload path (sha256 dedupe, the invoices bucket), is named\n`<stem>_p<n>.pdf`, keeps the parent's folder and carries `file_metadata.split_from` /\n`page_index`. The parent records `file_metadata.split_into` and, unless already analysed, is\nmarked `verdict.code = split_into_pages` so no drain re-reads the whole scan. One\n`audit_logs` row (`FILE_SPLIT`). The children are NOT analysed in this request — call\n`POST /file-uploads/{file_id}/analyze/queue` per child.\n\nRefused with 400 for a non-PDF, a 1-page PDF, a deleted file, an out-of-range page or more than\n20 pages in one request; 404 when the file is not the caller's. The parent is updated only after\nevery child exists, so a failed run leaves it unchanged (a retry dedupes to the children already made).",
        "parameters": [
          {
            "in": "path",
            "name": "file_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "additionalProperties": false,
                "properties": {
                  "pages": {
                    "description": "1-based page numbers to extract, at most 20 per request (400 above; a longer PDF is cut in ranges). Omit for every page.",
                    "items": {
                      "maximum": 2000,
                      "minimum": 1,
                      "type": "integer"
                    },
                    "maxItems": 20,
                    "minItems": 1,
                    "type": "array"
                  }
                },
                "type": "object"
              }
            }
          },
          "required": false
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "children": {
                          "items": {
                            "properties": {
                              "fileName": {
                                "example": "20261005_scan_p3.pdf",
                                "type": "string"
                              },
                              "id": {
                                "format": "uuid",
                                "type": "string"
                              },
                              "pageIndex": {
                                "example": 3,
                                "type": "integer"
                              }
                            },
                            "required": [
                              "id",
                              "fileName",
                              "pageIndex"
                            ],
                            "type": "object"
                          },
                          "type": "array"
                        },
                        "parentId": {
                          "format": "uuid",
                          "type": "string"
                        }
                      },
                      "required": [
                        "parentId",
                        "children"
                      ],
                      "type": "object"
                    },
                    "message": {
                      "example": "8 ページに分割しました",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "message",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Children created (or reused by sha256 dedupe)"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Split a multi-page PDF into one child file per page",
        "tags": [
          "File Upload"
        ]
      }
    },
    "/filing-amendment/amendments": {
      "get": {
        "parameters": [
          {
            "description": "When omitted, returns amendments for all fiscal years",
            "in": "query",
            "name": "fiscal_year",
            "required": false,
            "schema": {
              "example": 2025,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Amendment history (newest discovery first)"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List tax_amendments history (optional fiscal year filter)",
        "tags": [
          "Filing Amendment"
        ]
      }
    },
    "/filing-amendment/cancel": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "amendment_session_id": {
                    "format": "uuid",
                    "type": "string"
                  },
                  "fiscal_year": {
                    "type": "integer"
                  },
                  "reason": {
                    "type": "string"
                  }
                },
                "required": [
                  "fiscal_year",
                  "amendment_session_id"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Amendment cancelled"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Cancel an in-progress amendment session",
        "tags": [
          "Filing Amendment"
        ]
      }
    },
    "/filing-amendment/complete": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "amendment_session_id": {
                    "format": "uuid",
                    "type": "string"
                  },
                  "fiscal_year": {
                    "type": "integer"
                  },
                  "reason": {
                    "type": "string"
                  }
                },
                "required": [
                  "fiscal_year",
                  "amendment_session_id",
                  "reason"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Amendment completed"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Complete an amendment session",
        "tags": [
          "Filing Amendment"
        ]
      }
    },
    "/filing-amendment/context": {
      "get": {
        "parameters": [
          {
            "in": "query",
            "name": "fiscal_year",
            "required": true,
            "schema": {
              "example": 2025,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Amendment context"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Read-only provenance context for amendment",
        "tags": [
          "Filing Amendment"
        ]
      }
    },
    "/filing-amendment/materiality-assessment": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "delta_payload": {
                    "type": "object"
                  },
                  "fiscal_year": {
                    "type": "integer"
                  },
                  "override_path": {
                    "type": "string"
                  },
                  "qualitative_factors": {
                    "type": "object"
                  },
                  "reason": {
                    "type": "string"
                  },
                  "tax_impact": {
                    "type": "object"
                  }
                },
                "required": [
                  "fiscal_year",
                  "reason",
                  "delta_payload"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Materiality assessment result + draft tax_amendments row"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "ASBJ #24 materiality assessment (does not open a session)",
        "tags": [
          "Filing Amendment"
        ]
      }
    },
    "/filing-amendment/memos": {
      "get": {
        "parameters": [
          {
            "in": "query",
            "name": "fiscal_year",
            "required": true,
            "schema": {
              "example": 2025,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Chronological memos"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List 監査メモ for a fiscal year",
        "tags": [
          "Filing Amendment"
        ]
      },
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "body": {
                    "type": "string"
                  },
                  "fiscal_year": {
                    "type": "integer"
                  },
                  "title": {
                    "type": "string"
                  }
                },
                "required": [
                  "fiscal_year",
                  "title",
                  "body"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Memo appended"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Append a 監査メモ",
        "tags": [
          "Filing Amendment"
        ]
      }
    },
    "/filing-amendment/penalty-estimate": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Penalty estimate"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Estimate amendment penalties / reconcile tax impact",
        "tags": [
          "Filing Amendment"
        ]
      }
    },
    "/filing-amendment/start": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "fiscal_year": {
                    "type": "integer"
                  },
                  "reason": {
                    "type": "string"
                  }
                },
                "required": [
                  "fiscal_year",
                  "reason"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Amendment session started"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Open an amendment session",
        "tags": [
          "Filing Amendment"
        ]
      }
    },
    "/filing-amendment/status": {
      "get": {
        "parameters": [
          {
            "in": "query",
            "name": "fiscal_year",
            "required": true,
            "schema": {
              "example": 2025,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Amendment status"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Current amendment status for a fiscal year",
        "tags": [
          "Filing Amendment"
        ]
      }
    },
    "/filing-receipts/confirm": {
      "post": {
        "description": "Each file is read again now (downloaded, or the archive’s own text) and applied only when it still matches that deadline and only that one, and the deadline is still open. Applied through the 「提出しました」 path (kind filed: a row whose payment is not yet seen stays open as 提出済・納付待ち), with the receipt’s date, method, 受付番号 and the file as the 控え; an archived 受信通知 is saved as an upload first. Writes a deadline_audit_events row per applied item and syncs Google Calendar once. A refused item is in skipped with a reason.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "additionalProperties": false,
                "properties": {
                  "items": {
                    "items": {
                      "additionalProperties": false,
                      "properties": {
                        "deadlineId": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "fileId": {
                          "format": "uuid",
                          "type": "string"
                        }
                      },
                      "required": [
                        "fileId",
                        "deadlineId"
                      ],
                      "type": "object"
                    },
                    "maxItems": 20,
                    "minItems": 1,
                    "type": "array"
                  }
                },
                "required": [
                  "items"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "applied": {
                          "items": {
                            "properties": {
                              "deadlineId": {
                                "format": "uuid",
                                "type": "string"
                              },
                              "fileId": {
                                "format": "uuid",
                                "type": "string"
                              },
                              "paymentPending": {
                                "type": "boolean"
                              },
                              "status": {
                                "description": "`completed`, or the open status while the payment is owed",
                                "type": "string"
                              }
                            },
                            "required": [
                              "fileId",
                              "deadlineId",
                              "status",
                              "paymentPending"
                            ],
                            "type": "object"
                          },
                          "type": "array"
                        },
                        "skipped": {
                          "items": {
                            "properties": {
                              "fileId": {
                                "format": "uuid",
                                "type": "string"
                              },
                              "reason": {
                                "type": "string"
                              }
                            },
                            "required": [
                              "fileId",
                              "reason"
                            ],
                            "type": "object"
                          },
                          "type": "array"
                        }
                      },
                      "required": [
                        "applied",
                        "skipped"
                      ],
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "What was recorded and what was not"
          },
          "400": {
            "description": "Validation error (RFC 9457)"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Record the confirmed pairs as 提出済み",
        "tags": [
          "Filing receipts"
        ]
      }
    },
    "/filing-receipts/intake": {
      "post": {
        "description": "Each file is saved as the caller’s upload (deduped by SHA-256: the same file twice reuses its row), its text read (PDF text layer, or the XML as text), and matched to the caller’s open deadlines: the rule its 手続 names, due within 60 days before to 120 days after the filing date, the same 提出先 and 事業年度 when both sides state them. Exactly one candidate → suggestion; otherwise none. Nothing is completed. The request must fit 6 MB in all (5 MB per file).",
        "requestBody": {
          "content": {
            "multipart/form-data": {
              "schema": {
                "properties": {
                  "files": {
                    "items": {
                      "format": "binary",
                      "type": "string"
                    },
                    "maxItems": 20,
                    "type": "array"
                  }
                },
                "required": [
                  "files"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/FilingReceiptItems"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "One item per file, in order"
          },
          "400": {
            "description": "No file (RFC 9457)"
          },
          "401": {
            "description": "Unauthorized"
          },
          "413": {
            "description": "A file over 5 MB, more than 20 files, or a request over 6 MB"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Take in 控え files (PDF / XML, up to 20): save each, read it, suggest the deadline it closes",
        "tags": [
          "Filing receipts"
        ]
      }
    },
    "/filing-receipts/suggestions": {
      "get": {
        "description": "The 50 newest archived 受信通知 (filing_workspace_files, category receipt) with a 受付番号 no deadline records yet, and the intake files of the last 30 days not yet any deadline’s 控え — only those that match exactly one open deadline. Reads cached facts; downloads nothing.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/FilingReceiptItems"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Matched items only"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Pending suggestions: archived e-Tax 受信通知 and recent intake files that still close an open row",
        "tags": [
          "Filing receipts"
        ]
      }
    },
    "/filing-workspace/compare": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Compare result"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Compare workspace files vs live ledger",
        "tags": [
          "Filing Workspace"
        ]
      }
    },
    "/filing-workspace/files": {
      "get": {
        "responses": {
          "200": {
            "description": "File list"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List workspace filing files",
        "tags": [
          "Filing Workspace"
        ]
      }
    },
    "/filing-workspace/files/import": {
      "post": {
        "requestBody": {
          "content": {
            "multipart/form-data": {
              "schema": {
                "properties": {
                  "file": {
                    "format": "binary",
                    "type": "string"
                  }
                },
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "File imported"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Import a filing file (multipart)",
        "tags": [
          "Filing Workspace"
        ]
      }
    },
    "/filing-workspace/files/{id}": {
      "delete": {
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "File deleted"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Delete a workspace file",
        "tags": [
          "Filing Workspace"
        ]
      },
      "get": {
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "File detail"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get a workspace file by id",
        "tags": [
          "Filing Workspace"
        ]
      },
      "put": {
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "File updated"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update workspace file metadata",
        "tags": [
          "Filing Workspace"
        ]
      }
    },
    "/filing-workspace/files/{id}/duplicate": {
      "post": {
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Duplicated file"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Duplicate a workspace file",
        "tags": [
          "Filing Workspace"
        ]
      }
    },
    "/findings": {
      "get": {
        "description": "全エンジンの指摘をレンズ (triage / engine / period) でフィルタして返す。",
        "parameters": [
          {
            "in": "query",
            "name": "lens",
            "schema": {
              "enum": [
                "triage",
                "engine",
                "period"
              ],
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "scope",
            "schema": {
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "fiscal_year",
            "schema": {
              "type": "integer"
            }
          },
          {
            "description": "月 (1–12)。FindingsQuerySchema が受け付けるのは月番号のみ。",
            "in": "query",
            "name": "month",
            "schema": {
              "example": "6",
              "pattern": "^(0?[1-9]|1[0-2])$",
              "type": "string"
            }
          },
          {
            "description": "true / 1: counts only — `findings` is returned empty and `summary` is computed over the full set (badge / chip surfaces). Smaller payload only: the server runs the same full review, so the counts always match the list.",
            "in": "query",
            "name": "summary",
            "schema": {
              "enum": [
                "true",
                "false",
                "1",
                "0"
              ],
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FindingsListResult"
                }
              }
            },
            "description": "指摘一覧"
          },
          "401": {
            "description": "未認証"
          }
        },
        "summary": "統合指摘一覧",
        "tags": [
          "Findings"
        ]
      }
    },
    "/findings/acknowledge": {
      "post": {
        "description": "Append-only acknowledgment keyed by check_rule. True reds / blockers are not ackable. See finding-acknowledgment.service.ts.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "check_rule": {
                    "maxLength": 100,
                    "minLength": 1,
                    "type": "string"
                  },
                  "finding_snapshot": {
                    "properties": {
                      "details": {
                        "nullable": true,
                        "type": "string"
                      },
                      "legal_basis": {
                        "nullable": true,
                        "type": "string"
                      },
                      "name": {
                        "type": "string"
                      },
                      "severity": {
                        "type": "string"
                      },
                      "type": {
                        "type": "string"
                      }
                    },
                    "required": [
                      "type",
                      "name",
                      "severity"
                    ],
                    "type": "object"
                  },
                  "reason": {
                    "maxLength": 2000,
                    "minLength": 8,
                    "type": "string"
                  }
                },
                "required": [
                  "check_rule",
                  "reason",
                  "finding_snapshot"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/AckRow"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Acknowledgment recorded"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetails"
                }
              },
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetails"
                }
              }
            },
            "description": "Validation failed, or the finding is a blocker that cannot be acknowledged (details.reason ERR_ACK_NON_ACKABLE)"
          },
          "401": {
            "description": "未認証"
          }
        },
        "summary": "Acknowledge a non-blocking finding (working paper)",
        "tags": [
          "Findings"
        ]
      }
    },
    "/findings/acknowledgments": {
      "get": {
        "description": "Newest first. Revoked rows are left out unless include_revoked is 1 / true.",
        "parameters": [
          {
            "in": "query",
            "name": "check_rule",
            "schema": {
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "include_revoked",
            "schema": {
              "enum": [
                "0",
                "1",
                "true",
                "false"
              ],
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "items": {
                        "$ref": "#/components/schemas/AckRow"
                      },
                      "type": "array"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Acknowledgment rows"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetails"
                }
              },
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetails"
                }
              }
            },
            "description": "Invalid query"
          },
          "401": {
            "description": "未認証"
          }
        },
        "summary": "List acknowledgments",
        "tags": [
          "Findings"
        ]
      }
    },
    "/findings/acknowledgments/export": {
      "get": {
        "parameters": [
          {
            "description": "Defaults to the current calendar year",
            "in": "query",
            "name": "fiscal_year",
            "schema": {
              "maximum": 2100,
              "minimum": 1900,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "text/csv": {
                "schema": {
                  "type": "string"
                }
              }
            },
            "description": "CSV (UTF-8 with BOM) for the 15_確認記録.csv audit pack file"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetails"
                }
              },
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetails"
                }
              }
            },
            "description": "fiscal_year is not an integer in 1900–2100"
          },
          "401": {
            "description": "未認証"
          }
        },
        "summary": "Export acknowledgments CSV for a fiscal year",
        "tags": [
          "Findings"
        ]
      }
    },
    "/findings/acknowledgments/{id}/revoke": {
      "post": {
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "revoke_reason": {
                    "description": "Defaults to 取消",
                    "maxLength": 500,
                    "type": "string"
                  }
                },
                "type": "object"
              }
            }
          },
          "required": false
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/AckRow"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Revoked"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetails"
                }
              },
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetails"
                }
              }
            },
            "description": "revoke_reason is longer than 500 characters"
          },
          "401": {
            "description": "未認証"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetails"
                }
              },
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetails"
                }
              }
            },
            "description": "No acknowledgment with this id for the caller"
          },
          "409": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetails"
                }
              },
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetails"
                }
              }
            },
            "description": "Already revoked"
          }
        },
        "summary": "Revoke an acknowledgment (sets revoked_at; never deletes)",
        "tags": [
          "Findings"
        ]
      }
    },
    "/findings/dismiss": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "category": {
                    "type": "string"
                  },
                  "detail": {
                    "type": "string"
                  },
                  "id": {
                    "description": "CanonicalFinding.id",
                    "minLength": 1,
                    "type": "string"
                  },
                  "ignored_reason": {
                    "type": "string"
                  },
                  "title": {
                    "type": "string"
                  },
                  "triage": {
                    "enum": [
                      "high",
                      "medium",
                      "low"
                    ],
                    "type": "string"
                  }
                },
                "required": [
                  "id"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "却下完了"
          },
          "400": {
            "description": "Validation failed (id missing or triage out of range)"
          },
          "401": {
            "description": "未認証"
          }
        },
        "summary": "指摘を却下",
        "tags": [
          "Findings"
        ]
      }
    },
    "/fixed-assets": {
      "get": {
        "description": "Retrieve all fixed assets with linked bank transaction and document details.\n      \n## Query Parameters\n- **company_id**: Filter by company (optional)\n\n## Response Includes\n- Fixed asset details\n- Linked bank transaction info\n- Linked document info\n- Journal entry details",
        "parameters": [
          {
            "description": "Filter by company ID",
            "in": "query",
            "name": "company_id",
            "required": false,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "items": {
                        "$ref": "#/components/schemas/FixedAssetWithTransaction"
                      },
                      "type": "array"
                    },
                    "message": {
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Fixed assets retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get all fixed assets",
        "tags": [
          "Fixed Assets"
        ]
      },
      "post": {
        "description": "Create a new fixed asset record with Japanese tax law compliance and depreciation calculation.\n\n## Fixed Asset Management\nCreates comprehensive asset record with:\n- **Asset Classification**: Japanese Corporate Tax Law (法人税法) compliant classifications\n- **Depreciation Setup**: Automatic depreciation calculation based on method and useful life\n- **Financial Tracking**: Acquisition cost, book values, and depreciation amounts\n- **Document Integration**: Links to purchase orders, invoices, and supporting documentation\n- **Location Tracking**: Physical location and asset management information\n\n## Japanese Asset Classifications (資産区分)\nStandard Japanese tax law asset categories:\n- **建物 (Buildings)**: Office buildings, factories, warehouses\n- **建物附属設備 (Building Fixtures)**: Electrical, plumbing, HVAC systems\n- **構築物 (Structures)**: Roads, bridges, parking lots, landscaping\n- **機械装置 (Machinery)**: Production equipment, manufacturing machinery\n- **車両運搬具 (Vehicles)**: Company cars, trucks, delivery vehicles\n- **工具器具備品 (Tools & Equipment)**: Office equipment, computers, furniture\n- **土地 (Land)**: Real estate, building sites (non-depreciable)\n- **ソフトウェア (Software)**: Business software, licenses, systems\n- **その他 (Other)**: Assets not fitting standard classifications\n\n## Depreciation Methods (減価償却方法)\nJapanese accounting standard depreciation methods:\n- **定額法 (Straight Line)**: Equal annual depreciation over useful life\n- **定率法 (Declining Balance)**: Accelerated depreciation method\n- **旧定額法 (Old Straight Line)**: Legacy straight line method for older assets\n- **旧定率法 (Old Declining Balance)**: Legacy declining balance for older assets\n\n## Financial Calculations\nPrecise financial tracking with:\n- **Acquisition Cost**: Original purchase price including setup costs\n- **Opening Book Value**: Asset value at beginning of fiscal period\n- **Closing Book Value**: Asset value at end of fiscal period\n- **Depreciation Cost**: Annual depreciation expense calculation\n- **Useful Life**: Expected service life for depreciation purposes\n\n## Compliance Features\n- **Tax Law Alignment**: Classifications match Japanese Corporate Tax Law\n- **Audit Trail**: Complete history of asset creation and modifications\n- **Document Links**: Integration with purchase and disposal documentation\n- **Reporting Ready**: Data structured for Japanese tax and financial reporting\n- **Multi-Currency**: Support for foreign asset acquisitions with JPY conversion\n\n## Use Cases\n- **Asset Acquisition**: Record new equipment and property purchases\n- **Tax Compliance**: Maintain records for Japanese tax reporting\n- **Depreciation Planning**: Calculate and track asset depreciation schedules\n- **Audit Preparation**: Comprehensive asset documentation for audits\n- **Financial Reporting**: Asset data for balance sheet and P&L reporting\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "computer_equipment": {
                  "summary": "Office computer equipment",
                  "value": {
                    "acquisition_cost": 150000,
                    "acquisition_date": 20240115,
                    "classification": 6,
                    "closing_book_value": 120000,
                    "depreciation_cost": 30000,
                    "depreciation_method": 1,
                    "document_id": "456e7890-f12a-34b5-c678-901234567890",
                    "location": "本社 3階 営業部",
                    "name": "デスクトップコンピュータ Dell OptiPlex 7090",
                    "opening_book_value": 150000,
                    "quantity": 1,
                    "remarks": "保証期間: 2027年1月まで",
                    "unit": "台",
                    "useful_life": 4
                  }
                },
                "software_license": {
                  "summary": "Software license",
                  "value": {
                    "acquisition_cost": 180000,
                    "acquisition_date": 20240301,
                    "classification": 8,
                    "closing_book_value": 120000,
                    "depreciation_cost": 60000,
                    "depreciation_method": 1,
                    "document_id": "abc12345-def6-7890-ghij-klmnopqrstuv",
                    "location": "クラウドサービス",
                    "name": "Microsoft Office 365 Business Premium ライセンス",
                    "opening_book_value": 180000,
                    "quantity": 10,
                    "remarks": "年間契約 10ユーザー",
                    "unit": "ライセンス",
                    "useful_life": 3
                  }
                },
                "vehicle_asset": {
                  "summary": "Company vehicle",
                  "value": {
                    "acquisition_cost": 2800000,
                    "acquisition_date": 20240201,
                    "classification": 5,
                    "closing_book_value": 1960000,
                    "depreciation_cost": 466667,
                    "depreciation_method": 1,
                    "document_id": "789e0123-e45b-67c8-d901-234567890123",
                    "location": "本社駐車場 A-15",
                    "name": "トヨタ プリウス 営業車両",
                    "opening_book_value": 2800000,
                    "quantity": 1,
                    "remarks": "ナンバー: 品川 500 あ 1234",
                    "unit": "台",
                    "useful_life": 6
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/CreateFixedAssetRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FixedAssetCreateResponse"
                }
              }
            },
            "description": "Fixed asset created successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Invalid asset data or missing required fields",
                      "type": "string"
                    },
                    "fieldErrors": {
                      "additionalProperties": {
                        "items": {
                          "type": "string"
                        },
                        "type": "array"
                      },
                      "example": {
                        "acquisition_cost": [
                          "Acquisition cost must be a positive number"
                        ],
                        "classification": [
                          "Classification must be in 1, 2, 3, 4, 5, 6, 7, 8, 9"
                        ]
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid request data or validation errors"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Associated document not found or access denied",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Associated document not found"
          },
          "409": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "DUPLICATE_FIXED_ASSET",
                      "type": "string"
                    },
                    "error": {
                      "example": "Fixed asset already exists: \"デスクトップコンピュータ\" acquired on 20240115 for 150000",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Duplicate fixed asset detected"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create fixed asset",
        "tags": [
          "Fixed Assets"
        ]
      }
    },
    "/fixed-assets/amortization-schedule": {
      "post": {
        "description": "Calculate a fixed asset amortization/depreciation schedule using Japanese methods.\n\n## Supported Methods\n- **straight_line (定額法)**: Equal annual depreciation\n- **declining_balance (定率法)**: Declining balance with guarantee amount switching\n- **lump_sum (一括償却)**: 3-year equal depreciation for assets under ¥200,000\n\n## Japanese Tax Law Compliance\n- Uses statutory useful life from Japanese tax law asset categories\n- Declining balance uses 定率法 guarantee amounts and revised rates\n- Handles residual value (備忘価額 = ¥1)\n- Supports mid-year acquisition (月割計算)",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "acquisition_cost": {
                    "example": 1000000,
                    "minimum": 1,
                    "type": "number"
                  },
                  "acquisition_date": {
                    "example": "2026-04-15",
                    "format": "date",
                    "type": "string"
                  },
                  "method": {
                    "enum": [
                      "straight_line",
                      "declining_balance",
                      "lump_sum"
                    ],
                    "example": "declining_balance",
                    "type": "string"
                  },
                  "residual_value": {
                    "default": 1,
                    "example": 1,
                    "minimum": 0,
                    "type": "number"
                  },
                  "useful_life": {
                    "example": 5,
                    "maximum": 50,
                    "minimum": 2,
                    "type": "integer"
                  }
                },
                "required": [
                  "acquisition_cost",
                  "useful_life",
                  "method"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "acquisition_cost": {
                          "type": "number"
                        },
                        "method": {
                          "type": "string"
                        },
                        "residual_value": {
                          "type": "number"
                        },
                        "schedule": {
                          "items": {
                            "properties": {
                              "accumulated": {
                                "type": "number"
                              },
                              "closing_value": {
                                "type": "number"
                              },
                              "depreciation": {
                                "type": "number"
                              },
                              "opening_value": {
                                "type": "number"
                              },
                              "year": {
                                "type": "integer"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        },
                        "total_depreciation": {
                          "type": "number"
                        },
                        "useful_life": {
                          "type": "integer"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "償却スケジュールを計算しました",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Amortization schedule calculated"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Calculate amortization schedule (償却スケジュール計算)",
        "tags": [
          "Fixed Assets"
        ]
      }
    },
    "/fixed-assets/by-transaction/{bank_transaction_id}": {
      "get": {
        "description": "Find a fixed asset that is linked to a specific bank transaction.",
        "parameters": [
          {
            "description": "Bank transaction UUID",
            "in": "path",
            "name": "bank_transaction_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "oneOf": [
                        {
                          "$ref": "#/components/schemas/FixedAssetWithTransaction"
                        },
                        {
                          "type": "null"
                        }
                      ]
                    },
                    "message": {
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Fixed asset found (or null if not linked)"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Find fixed asset by bank transaction",
        "tags": [
          "Fixed Assets"
        ]
      }
    },
    "/fixed-assets/depreciable-asset-return": {
      "get": {
        "description": "Get depreciable asset return data (償却資産申告データ) for tax filing.\n\n## Overview\nThis endpoint analyzes all fixed assets and categorizes them by 償却資産申告 eligibility,\nproviding smart summaries and explanations for non-accountants.\n\n## 償却資産申告 Rules\nPer 地方税法 (Local Tax Law), the following assets are subject to declaration:\n\n### Subject to 償却資産申告 (申告対象)\n| Backend Classification | 地方税法 Category |\n|---|---|\n| 建物附属設備 (2) | 1: 構築物 |\n| 構築物 (3) | 1: 構築物 |\n| 機械装置 (4) | 2: 機械及び装置 |\n| 工具器具備品 (6) | 6: 工具、器具及び備品 |\n\n### NOT Subject (対象外)\n| Classification | Reason |\n|---|---|\n| 建物 (1) | Taxed via 登記 (property registration) |\n| 車両運搬具 (5) | Taxed via 自動車税 |\n| 土地 (7) | Taxed via 固定資産税 (登記) |\n| ソフトウェア (8) | Intangible asset, not taxable |\n\n### Additional Exclusions\n- Assets with acquisition cost < ¥100,000 (immediate expense items)\n\n## Response Categories\nThe response groups assets into three categories:\n\n1. **taxableAssets**: Assets subject to 償却資産申告\n   - Includes 地方税法 category mapping\n   - Includes evaluated value (150% declining balance method)\n\n2. **exemptAssets**: Assets NOT subject to declaration\n   - Includes clear Japanese explanation of why exempt\n   - Includes exemption code for frontend display\n\n3. **reviewRequired**: Assets needing manual review\n   - Typically \"その他\" classification\n   - Needs accountant judgment\n\n## Evaluated Value Calculation\nFor taxable assets, the `evaluatedValue` is calculated using:\n- 150% declining balance method (1.5倍定率法)\n- Minimum value: 5% of acquisition cost (残存価額)\n\n## Filing Timeline\n- **賦課期日**: January 1st of filing year\n- **申告期限**: January 31st (eLTAX submission)\n\n## Use Cases\n- Generate 償却資産申告書 from 固定資産台帳\n- Review which assets need to be declared\n- Understand why certain assets are exempt\n- Calculate total taxable value for budgeting",
        "parameters": [
          {
            "description": "Filing year (default: current year). Data is as of January 1st of this year.",
            "in": "query",
            "name": "year",
            "required": false,
            "schema": {
              "example": 2026,
              "type": "integer"
            }
          },
          {
            "description": "Filter by company ID",
            "in": "query",
            "name": "company_id",
            "required": false,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "no_taxable_assets": {
                    "summary": "Example with no taxable assets",
                    "value": {
                      "data": {
                        "asOfDate": 20260101,
                        "exemptAssets": [
                          {
                            "acquisitionCost": 3500000,
                            "acquisitionDate": 20250601,
                            "classification": 5,
                            "classificationName": "車両運搬具",
                            "exemptCode": "VEHICLE_TAX",
                            "exemptReason": "車両運搬具は自動車税で課税されるため対象外",
                            "id": "123e4567-e89b-12d3-a456-426614174005",
                            "name": "営業用車両"
                          }
                        ],
                        "filingYear": 2026,
                        "reviewRequired": [],
                        "summary": {
                          "byCategory": {},
                          "totalExemptAssets": 1,
                          "totalReviewRequired": 0,
                          "totalTaxableAssets": 0,
                          "totalTaxableValue": 0
                        },
                        "taxableAssets": []
                      },
                      "message": "償却資産申告データを取得しました",
                      "statusCode": 200
                    }
                  },
                  "with_assets": {
                    "summary": "Example with multiple asset types",
                    "value": {
                      "data": {
                        "asOfDate": 20260101,
                        "exemptAssets": [
                          {
                            "acquisitionCost": 2945397,
                            "acquisitionDate": 20241201,
                            "classification": 5,
                            "classificationName": "車両運搬具",
                            "exemptCode": "VEHICLE_TAX",
                            "exemptReason": "車両運搬具は自動車税で課税されるため対象外",
                            "id": "123e4567-e89b-12d3-a456-426614174003",
                            "name": "スズキ ジムニー シエラ（JB74W）"
                          },
                          {
                            "acquisitionCost": 180000,
                            "acquisitionDate": 20250401,
                            "classification": 8,
                            "classificationName": "ソフトウェア",
                            "exemptCode": "INTANGIBLE_ASSET",
                            "exemptReason": "ソフトウェアは無形固定資産のため対象外",
                            "id": "123e4567-e89b-12d3-a456-426614174004",
                            "name": "Microsoft 365 ライセンス"
                          }
                        ],
                        "filingYear": 2026,
                        "reviewRequired": [],
                        "summary": {
                          "byCategory": {
                            "1": {
                              "count": 1,
                              "name": "構築物",
                              "value": 315000
                            },
                            "6": {
                              "count": 1,
                              "name": "工具、器具及び備品",
                              "value": 131250
                            }
                          },
                          "totalExemptAssets": 2,
                          "totalReviewRequired": 0,
                          "totalTaxableAssets": 2,
                          "totalTaxableValue": 446250
                        },
                        "taxableAssets": [
                          {
                            "acquisitionCost": 350000,
                            "acquisitionDate": 20250615,
                            "classification": 2,
                            "classificationName": "建物附属設備",
                            "closingBookValue": 280000,
                            "depreciationMethod": 1,
                            "evaluatedValue": 315000,
                            "id": "123e4567-e89b-12d3-a456-426614174001",
                            "location": "オフィス 3階",
                            "name": "業務用エアコン",
                            "openingBookValue": 350000,
                            "reason": "申告対象",
                            "remarks": null,
                            "taxCategory": 1,
                            "taxCategoryName": "構築物",
                            "usefulLife": 15
                          },
                          {
                            "acquisitionCost": 150000,
                            "acquisitionDate": 20250301,
                            "classification": 6,
                            "classificationName": "工具器具備品",
                            "closingBookValue": 112500,
                            "depreciationMethod": 1,
                            "evaluatedValue": 131250,
                            "id": "123e4567-e89b-12d3-a456-426614174002",
                            "location": "本社 営業部",
                            "name": "デスクトップPC Dell OptiPlex",
                            "openingBookValue": 150000,
                            "reason": "申告対象",
                            "remarks": null,
                            "taxCategory": 6,
                            "taxCategoryName": "工具、器具及び備品",
                            "usefulLife": 4
                          }
                        ]
                      },
                      "message": "償却資産申告データを取得しました",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/DepreciableAssetReturnResponse"
                }
              }
            },
            "description": "償却資産申告データを取得しました"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "償却資産申告データ取得",
        "tags": [
          "Fixed Assets"
        ]
      }
    },
    "/fixed-assets/from-transaction": {
      "post": {
        "description": "Create a new fixed asset directly from a bank transaction.\n\n## 固定資産購入 Workflow\nThis endpoint supports the \"固定資産購入\" (Fixed Asset Purchase) workflow:\n1. User selects a bank transaction (e.g., ¥2,945,397 car purchase)\n2. Selects \"固定資産購入\" workflow option\n3. System auto-populates acquisition date and cost from transaction\n4. User provides asset details (name, classification, depreciation method)\n5. System creates fixed asset linked to the transaction\n\n## Auto-populated Fields\nFrom bank transaction:\n- **acquisition_date**: Transaction date\n- **acquisition_cost**: Withdrawal amount\n- **opening_book_value**: Same as acquisition cost\n- **journal_entry_id**: If transaction has journal entry\n\n## Use Cases\n- Vehicle purchases (車両購入)\n- Equipment purchases (設備購入)\n- Property purchases (不動産購入)\n- Large item purchases exceeding ¥100,000",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "equipment_purchase": {
                  "summary": "Equipment purchase (設備購入)",
                  "value": {
                    "bank_transaction_id": "456e7890-f12a-34b5-c678-901234567890",
                    "classification": 2,
                    "depreciation_method": 1,
                    "location": "オフィス 3階",
                    "name": "業務用エアコン",
                    "useful_life": 15
                  }
                },
                "vehicle_purchase": {
                  "summary": "Vehicle purchase (車両購入)",
                  "value": {
                    "bank_transaction_id": "123e4567-e89b-12d3-a456-426614174000",
                    "classification": 5,
                    "depreciation_method": 1,
                    "location": "本社駐車場",
                    "name": "ジムニー中古車",
                    "remarks": "営業用車両 - Gulliver購入",
                    "useful_life": 6
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/CreateFixedAssetFromTransactionRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FixedAssetLinkResponse"
                }
              }
            },
            "description": "Fixed asset created from transaction"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid request data"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Bank transaction not found or access denied",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Bank transaction not found"
          },
          "409": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Bank transaction already linked to fixed asset: ジムニー (ID: xxx)",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Transaction already linked to another asset"
          },
          "423": {
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetails"
                }
              }
            },
            "description": "The bank row already carries 証憑 (a document link or a file), and the 仕訳 this call attaches to it is in a filed or closed 課税期間, including a quarter whose return is filed while its period row is still open (PERIOD_LOCKED). Allowed inside a 修正申告 for that fiscal year."
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create fixed asset from bank transaction (固定資産購入)",
        "tags": [
          "Fixed Assets"
        ]
      }
    },
    "/fixed-assets/{fixed_asset_id}": {
      "delete": {
        "description": "Soft delete a fixed asset record while maintaining audit trail and compliance history.\n\n## Soft Deletion Process\nPerforms comprehensive asset deletion with:\n- **Soft Delete**: Asset marked as deleted without physical removal\n- **Audit Preservation**: Complete asset history maintained for compliance\n- **Timestamp Recording**: Deletion date and time recorded for audit\n- **Access Restriction**: Deleted assets excluded from normal operations\n- **Recovery Capability**: Potential for asset recovery if needed\n\n## Compliance Considerations\n- **Tax Law Requirements**: Deleted assets maintained for tax audit purposes\n- **Audit Trail**: Complete deletion history for regulatory compliance\n- **Financial Reporting**: Proper handling of disposed assets in reports\n- **Documentation**: Deletion reasons and authorization tracking\n- **Recovery Procedures**: Process for asset recovery if deletion was in error\n\n## Asset Disposal Workflow\nDeletion supports asset disposal process:\n- **Pre-Disposal**: Mark asset for disposal planning\n- **Disposal Authorization**: Management approval for asset disposal\n- **Final Deletion**: Formal removal from active asset register\n- **Post-Disposal**: Maintain records for compliance and audit\n- **Reporting**: Include disposed assets in disposal reports\n\n## Security Measures\n- **Ownership Verification**: Only asset owner can delete the asset\n- **Access Control**: Proper authorization required for deletion\n- **Audit Logging**: Complete logging of deletion operations\n- **Data Protection**: Sensitive asset data handled securely\n- **Compliance**: Deletion process follows regulatory requirements\n\n## Use Cases\n- **Asset Disposal**: Remove assets that have been physically disposed\n- **Error Correction**: Delete assets created in error\n- **End of Life**: Remove assets at end of useful life\n- **Compliance**: Maintain proper asset disposal documentation\n- **Audit Preparation**: Clean up asset register for audit purposes\n\n## Recovery Considerations\n- **Soft Delete Benefits**: Assets can potentially be recovered\n- **Audit Requirements**: Deleted assets remain for audit purposes\n- **Data Retention**: Compliance with data retention policies\n- **Recovery Process**: Administrative process for asset recovery\n- **Historical Integrity**: Maintain complete asset lifecycle history\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the fixed asset to delete",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "in": "path",
            "name": "fixed_asset_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FixedAssetDeleteResponse"
                }
              }
            },
            "description": "Fixed asset deleted successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Invalid fixed asset ID format",
                      "type": "string"
                    },
                    "fieldErrors": {
                      "properties": {
                        "fixed_asset_id": {
                          "example": [
                            "Invalid fixed asset ID format"
                          ],
                          "items": {
                            "type": "string"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid asset ID format"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Access denied - insufficient permissions to delete this asset",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Access denied - asset belongs to different user"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Fixed asset not found or already deleted",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Fixed asset not found or already deleted"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Delete fixed asset",
        "tags": [
          "Fixed Assets"
        ]
      },
      "put": {
        "description": "Update an existing fixed asset record with validation and audit trail maintenance.\n\n## Asset Update Operations\nSupports comprehensive asset updates including:\n- **Asset Information**: Name, classification, and descriptive details\n- **Financial Data**: Acquisition costs, book values, and depreciation amounts\n- **Location Changes**: Asset relocation and physical management\n- **Depreciation Adjustments**: Method changes and useful life updates\n- **Documentation**: Remarks and additional asset information\n\n## Update Validation\n- **Ownership Verification**: User must own the asset being updated\n- **Financial Consistency**: Book values and depreciation amounts validated\n- **Classification Rules**: Asset classification changes validated for tax compliance\n- **Depreciation Logic**: Useful life and method changes validated for consistency\n- **Document References**: Associated document access verified\n\n## Japanese Tax Compliance\nUpdates maintain compliance with:\n- **Corporate Tax Law**: Asset classification and depreciation rules\n- **Accounting Standards**: Japanese GAAP depreciation methods\n- **Audit Requirements**: Change tracking and documentation\n- **Reporting Standards**: Financial reporting consistency\n- **Tax Reporting**: Proper categorization for tax filings\n\n## Depreciation Recalculation\nWhen depreciation parameters change:\n- **Method Changes**: Automatic recalculation with new method\n- **Useful Life Updates**: Remaining depreciation schedule adjustment\n- **Book Value Adjustments**: Consistency checks and validation\n- **Historical Preservation**: Previous calculations maintained for audit\n\n## Use Cases\n- **Asset Maintenance**: Update asset information and location\n- **Financial Adjustments**: Correct acquisition costs and book values\n- **Depreciation Changes**: Update depreciation methods or useful life\n- **Location Tracking**: Record asset moves and relocations\n- **Documentation Updates**: Add remarks and additional information\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the fixed asset to update",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "in": "path",
            "name": "fixed_asset_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "comprehensive_update": {
                  "summary": "Comprehensive asset update",
                  "value": {
                    "acquisition_cost": 155000,
                    "closing_book_value": 124000,
                    "location": "本社 4階 開発部",
                    "name": "デスクトップコンピュータ Dell OptiPlex 7090 (アップグレード済み)",
                    "opening_book_value": 155000,
                    "remarks": "メモリ増設およびSSD換装完了"
                  }
                },
                "depreciation_adjustment": {
                  "summary": "Adjust depreciation method",
                  "value": {
                    "closing_book_value": 100000,
                    "depreciation_method": 2,
                    "remarks": "税務調整により定率法に変更",
                    "useful_life": 5
                  }
                },
                "location_update": {
                  "summary": "Update asset location",
                  "value": {
                    "location": "本社 2階 総務部",
                    "remarks": "部署移転により移動 - 2024年4月"
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/UpdateFixedAssetRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FixedAssetUpdateResponse"
                }
              }
            },
            "description": "Fixed asset updated successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Invalid update data or financial inconsistency",
                      "type": "string"
                    },
                    "fieldErrors": {
                      "additionalProperties": {
                        "items": {
                          "type": "string"
                        },
                        "type": "array"
                      },
                      "example": {
                        "closing_book_value": [
                          "Closing book value cannot exceed opening book value"
                        ]
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid request data or validation errors"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Access denied - insufficient permissions to update this asset",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Access denied - asset belongs to different user"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Fixed asset not found or access denied",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Fixed asset not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update fixed asset",
        "tags": [
          "Fixed Assets"
        ]
      }
    },
    "/fixed-assets/{fixed_asset_id}/link-transaction": {
      "delete": {
        "description": "Remove the link between a fixed asset and its bank transaction.",
        "parameters": [
          {
            "description": "Fixed asset UUID",
            "in": "path",
            "name": "fixed_asset_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "id": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "unlinked_bank_transaction_id": {
                          "format": "uuid",
                          "type": "string"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Bank transaction unlinked from fixed asset",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Transaction unlinked successfully"
          },
          "400": {
            "description": "Asset is not linked to any transaction"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Fixed asset not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Unlink bank transaction from fixed asset",
        "tags": [
          "Fixed Assets"
        ]
      },
      "post": {
        "description": "Link an existing fixed asset to a bank transaction.\n      \nUse this when:\n- Fixed asset was created manually and later matched to a transaction\n- Reassigning a transaction to a different asset",
        "parameters": [
          {
            "description": "Fixed asset UUID",
            "in": "path",
            "name": "fixed_asset_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/LinkBankTransactionRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FixedAssetLinkResponse"
                }
              }
            },
            "description": "Transaction linked successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Fixed asset or bank transaction not found"
          },
          "409": {
            "description": "Transaction already linked to another asset"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Link bank transaction to existing fixed asset",
        "tags": [
          "Fixed Assets"
        ]
      }
    },
    "/folders": {
      "get": {
        "description": "Retrieve all folders belonging to the authenticated user with optional filtering.\n\n## Query Parameters\n- **folder_id**: Optional folder ID to filter by specific folder\n\n## Response Data\nReturns flat array of folders with complete information including:\n- Folder identification and naming\n- Hierarchical information (parent_id, level)\n- Visual customization (icon, color)\n- Associated document references\n- Audit timestamps and metadata\n\n## Folder Hierarchy\nThe system supports up to 3 levels of folder nesting:\n- **Level 0**: Root folders (no parent)\n- **Level 1**: First-level subfolders\n- **Level 2**: Second-level subfolders\n- **Level 3**: Maximum depth subfolders\n\n## Use Cases\n- Folder management interfaces\n- Document organization systems\n- File browser implementations\n- Content categorization\n\n## Security\nOnly returns folders belonging to the authenticated user.\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Optional folder ID to filter by",
            "in": "query",
            "name": "folder_id",
            "required": false,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FolderListResponse"
                }
              }
            },
            "description": "Folders retrieved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get all folders for user",
        "tags": [
          "Folders"
        ]
      },
      "post": {
        "description": "Create a new folder with optional parent-child relationship and visual customization.\n\n## Request Body\n- **name**: Folder name (required, 1-50 characters)\n- **description**: Optional folder description (max 200 characters)\n- **parent_id**: Optional parent folder ID for hierarchy\n- **icon**: Optional icon identifier for visual customization\n- **color**: Optional color (hex code or color name)\n- **document_id**: Optional associated document ID\n\n## Folder Hierarchy Rules\n- Maximum folder depth: 3 levels\n- Root folders have no parent_id (null)\n- Parent folder must exist and belong to user\n- Level is automatically calculated based on parent\n\n## Visual Customization\n- **Icons**: Support for various folder icon types\n- **Colors**: Hex codes (#RRGGBB) or named colors\n- **Themes**: Consistent visual organization\n- **User Preferences**: Customizable appearance\n\n## Validation Rules\n- Name must be 1-50 characters\n- Description limited to 200 characters\n- Parent folder must exist if specified\n- Maximum depth of 3 levels enforced\n- User must own parent folder if specified\n\n## Use Cases\n- Document organization and categorization\n- Project-based file management\n- Hierarchical content structure\n- Visual organization systems\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateFolderRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FolderCreateResponse"
                }
              }
            },
            "description": "Folder created successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "MAX_DEPTH_EXCEEDED",
                      "type": "string"
                    },
                    "error": {
                      "example": "Maximum folder depth of 3 levels exceeded",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid request or maximum depth exceeded"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "PARENT_NOT_FOUND",
                      "type": "string"
                    },
                    "error": {
                      "example": "Parent folder not found or access denied",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Parent folder not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create a new folder",
        "tags": [
          "Folders"
        ]
      }
    },
    "/folders/user": {
      "get": {
        "description": "Retrieve the complete hierarchical folder tree for the authenticated user.\n\n## Query Parameters\n- **rootParentId**: Optional root folder ID to get subtree from\n- **sortBy**: Sort criteria (name, created_at, level) - default: name\n- **sortOrder**: Sort order (asc, desc) - default: asc\n\n## Tree Structure\nReturns hierarchical folder structure with:\n- Recursive parent-child relationships\n- Nested children arrays\n- Complete folder metadata\n- Sorted results at each level\n\n## Sorting Options\n- **name**: Alphabetical sorting by folder name\n- **created_at**: Chronological sorting by creation date\n- **level**: Sorting by hierarchy level\n\n## Subtree Filtering\n- **rootParentId**: Returns only the specified folder and its descendants\n- **null/omitted**: Returns complete folder tree from all root folders\n- **Performance**: Reduces data transfer for large folder structures\n\n## Response Format\nEach folder node includes:\n- Complete folder information\n- Children array with nested folder nodes\n- Recursive structure for unlimited depth display\n- Optimized for tree view components\n\n## Use Cases\n- File browser tree views\n- Folder navigation interfaces\n- Hierarchical content organization\n- Document management systems\n\n## Performance Considerations\n- Tree building is optimized for large datasets\n- Recursive structure supports efficient rendering\n- Subtree filtering reduces payload size\n- Sorted results improve user experience\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Optional root folder ID to get subtree from",
            "in": "query",
            "name": "rootParentId",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "Sort criteria for folder ordering",
            "in": "query",
            "name": "sortBy",
            "required": false,
            "schema": {
              "default": "name",
              "enum": [
                "name",
                "created_at",
                "level"
              ],
              "type": "string"
            }
          },
          {
            "description": "Sort order for folder arrangement",
            "in": "query",
            "name": "sortOrder",
            "required": false,
            "schema": {
              "default": "asc",
              "enum": [
                "asc",
                "desc"
              ],
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FolderTreeResponse"
                }
              }
            },
            "description": "User folders tree retrieved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get user folders tree",
        "tags": [
          "Folders"
        ]
      }
    },
    "/folders/{folderId}": {
      "delete": {
        "description": "Delete a folder and all its contents including child folders and associated files.\n\n## Path Parameters\n- **folderId**: UUID of the folder to delete\n\n## Cascade Deletion\nThis endpoint performs comprehensive cleanup:\n- **Soft deletes** the target folder\n- **Recursively deletes** all child folders\n- **Removes associated** files and documents\n- **Cleans up** database relationships\n- **Maintains audit trail** of deletion operations\n\n## Deletion Impact\nDeleting a folder affects:\n- All child folders (recursive deletion)\n- Associated documents and files\n- File attachments and uploads\n- Folder-document relationships\n- User organization structure\n\n## Safety Measures\n- **Soft deletion**: Folders marked as deleted, not physically removed\n- **Audit logging**: All deletions logged for compliance\n- **User verification**: Only folder owners can delete\n- **Cascade protection**: Prevents orphaned records\n\n## Recovery Considerations\n- Soft-deleted folders may be recoverable\n- Associated files may be preserved in storage\n- Audit logs maintain deletion history\n- Recovery procedures may be available\n\n## Performance Notes\n- Large folder trees may take time to process\n- Deletion is performed in database transactions\n- Background cleanup may continue after response\n- Progress tracking available through logs\n\n## Use Cases\n- Folder cleanup and organization\n- Project completion cleanup\n- Storage space management\n- Data retention compliance\n\n## Authentication\nRequires valid Bearer token in Authorization header.\n\n## 仕訳の証憑 (je_link, BE ADR-0008)\nA file linked to a 仕訳 with `POST /file-uploads/{file_id}/link` (type `je_link`) is\nconsumption-tax evidence, so deleting it moves the credit exactly as an unlink does:\n- **423 PERIOD_LOCKED** when any linked 仕訳 falls in a filed / closed / audited\n  period, or in a 課税期間 with a filed return. Nothing is deleted.\n- Otherwise the links are deleted with the file, in one transaction, and\n  `meta.removedEvidenceLinks` in the 200 envelope counts them, so the client can\n  tell the user which evidence went.",
        "parameters": [
          {
            "description": "UUID of the folder to delete",
            "in": "path",
            "name": "folderId",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FolderDeleteResponse"
                }
              }
            },
            "description": "Folder deleted successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "ACCESS_DENIED",
                      "type": "string"
                    },
                    "error": {
                      "example": "Access denied",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Access denied - folder belongs to different user"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "423": {
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetails"
                }
              }
            },
            "description": "A file is 証憑 on a 仕訳 in a filed / closed period (PERIOD_LOCKED); nothing was deleted"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Delete folder",
        "tags": [
          "Folders"
        ]
      },
      "get": {
        "description": "Retrieve a specific folder by its unique identifier.\n\n## Path Parameters\n- **folderId**: UUID of the folder to retrieve\n\n## Response Data\nReturns complete folder information including:\n- Folder identification and naming\n- Hierarchical position (parent_id, level)\n- Visual customization (icon, color)\n- Associated document reference\n- Audit timestamps and metadata\n- Deletion status and timestamps\n\n## Folder Access\n- Only returns folders owned by the authenticated user\n- Includes soft-deleted folders with deletion metadata\n- Provides complete folder structure and relationships\n- Includes all customization and configuration data\n\n## Use Cases\n- Folder detail views\n- Folder editing forms\n- Hierarchy navigation\n- Folder management operations\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the folder to retrieve",
            "in": "path",
            "name": "folderId",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FolderResponse"
                }
              }
            },
            "description": "Folder retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "ACCESS_DENIED",
                      "type": "string"
                    },
                    "error": {
                      "example": "Access denied",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Access denied - folder belongs to different user"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get folder by ID",
        "tags": [
          "Folders"
        ]
      },
      "put": {
        "description": "Update an existing folder with new information.\n\n## Path Parameters\n- **folderId**: UUID of the folder to update\n\n## Request Body\nAll fields are optional for updates:\n- **name**: New folder name\n- **description**: Updated folder description\n- **icon**: New icon identifier\n- **color**: New color scheme\n\n## Update Behavior\n- Only provided fields are updated\n- Omitted fields remain unchanged\n- Name and description length validation applied\n- Visual customization updates immediately\n- Update timestamp is refreshed\n\n## Validation Rules\n- Folder must exist and belong to user\n- Name must be 1-50 characters if provided\n- Description limited to 200 characters if provided\n- Icon and color values are validated\n- Cannot update hierarchy (parent_id, level)\n\n## Restrictions\nCannot update via this endpoint:\n- Parent-child relationships (use move operations)\n- Folder hierarchy level\n- Associated document ID\n- User ownership\n- Deletion status\n\n## Use Cases\n- Folder renaming and description updates\n- Visual customization changes\n- Folder organization improvements\n- Content management updates\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the folder to update",
            "in": "path",
            "name": "folderId",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateFolderRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FolderResponse"
                }
              }
            },
            "description": "Folder updated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "ACCESS_DENIED",
                      "type": "string"
                    },
                    "error": {
                      "example": "Access denied",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Access denied - folder belongs to different user"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update folder",
        "tags": [
          "Folders"
        ]
      }
    },
    "/gamification/achievements/progress": {
      "post": {
        "description": "Update progress for a specific achievement. Returns tier upgrade info if applicable.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateAchievementRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/AchievementProgressResponse"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Progress updated"
          },
          "201": {
            "description": "Achievement unlocked"
          },
          "404": {
            "description": "Achievement not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update achievement progress (実績進捗更新)",
        "tags": [
          "Gamification"
        ]
      }
    },
    "/gamification/achievements/view": {
      "post": {
        "description": "Mark achievement notification as viewed.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "achievement_id": {
                    "example": "first_login",
                    "type": "string"
                  }
                },
                "required": [
                  "achievement_id"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Marked as viewed"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Mark achievement viewed (実績閲覧済み)",
        "tags": [
          "Gamification"
        ]
      }
    },
    "/gamification/definitions": {
      "get": {
        "description": "Get ALL gamification definitions in a single response. Combines levels, achievements, goals, XP rewards, and lookup tables.\n\n**v4.70:** Reduces 4 separate requests to 1 for frontend initial load.\n\n**Caching:** Browser 1h, CDN 24h. Definitions rarely change.\n\n**Frontend usage:**\n```typescript\nconst { data } = useQuery({\n  queryKey: ['gamification', 'definitions'],\n  queryFn: () => api.get('/gamification/definitions'),\n  staleTime: 24 * 60 * 60 * 1000, // 24h\n})\n```",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "achievementCategoryColors": {
                          "description": "Semantic color per category",
                          "example": {
                            "accounting": "indigo",
                            "onboarding": "green"
                          },
                          "type": "object"
                        },
                        "achievementTierLabels": {
                          "additionalProperties": {
                            "$ref": "#/components/schemas/BilingualLabel"
                          },
                          "description": "Achievement tier labels (ja/en)",
                          "type": "object"
                        },
                        "achievementTierXP": {
                          "description": "XP rewards per achievement tier",
                          "example": {
                            "bronze": 25,
                            "gold": 100,
                            "platinum": 200,
                            "silver": 50
                          },
                          "type": "object"
                        },
                        "achievements": {
                          "items": {
                            "$ref": "#/components/schemas/AchievementDefinition"
                          },
                          "type": "array"
                        },
                        "categoryLabels": {
                          "additionalProperties": {
                            "$ref": "#/components/schemas/BilingualLabel"
                          },
                          "description": "Achievement category labels (ja/en)",
                          "type": "object"
                        },
                        "goals": {
                          "items": {
                            "$ref": "#/components/schemas/GoalDefinition"
                          },
                          "type": "array"
                        },
                        "levels": {
                          "items": {
                            "$ref": "#/components/schemas/LevelDefinition"
                          },
                          "type": "array"
                        },
                        "meta": {
                          "properties": {
                            "achievements": {
                              "example": 25,
                              "type": "integer"
                            },
                            "goals": {
                              "example": 12,
                              "type": "integer"
                            },
                            "levels": {
                              "example": 30,
                              "type": "integer"
                            },
                            "xpRewards": {
                              "example": 18,
                              "type": "integer"
                            }
                          },
                          "type": "object"
                        },
                        "streakMultipliers": {
                          "description": "Streak day thresholds and their multipliers",
                          "example": {
                            "7": 1.1,
                            "30": 1.25,
                            "90": 1.5,
                            "365": 2
                          },
                          "type": "object"
                        },
                        "tierLabels": {
                          "additionalProperties": {
                            "$ref": "#/components/schemas/BilingualLabel"
                          },
                          "description": "Level tier labels (ja/en)",
                          "type": "object"
                        },
                        "xpRewards": {
                          "items": {
                            "$ref": "#/components/schemas/XPRewardDefinition"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "All definitions"
          },
          "401": {
            "description": "Not authenticated"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get all definitions (全定義取得)",
        "tags": [
          "Gamification"
        ]
      }
    },
    "/gamification/definitions/achievements": {
      "get": {
        "description": "Get all achievement definitions with categories, thresholds, and colors (v4.70).",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "achievements": {
                          "items": {
                            "$ref": "#/components/schemas/AchievementDefinition"
                          },
                          "type": "array"
                        },
                        "meta": {
                          "properties": {
                            "total": {
                              "example": 25,
                              "type": "integer"
                            }
                          },
                          "type": "object"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Achievement definitions"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get achievement definitions (実績定義)",
        "tags": [
          "Gamification"
        ]
      }
    },
    "/gamification/definitions/goals": {
      "get": {
        "description": "Get all goal definitions with navigation paths and prerequisites.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "goals": {
                          "items": {
                            "$ref": "#/components/schemas/GoalDefinition"
                          },
                          "type": "array"
                        },
                        "meta": {
                          "properties": {
                            "total": {
                              "example": 12,
                              "type": "integer"
                            }
                          },
                          "type": "object"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Goal definitions"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get goal definitions (ゴール定義)",
        "tags": [
          "Gamification"
        ]
      }
    },
    "/gamification/definitions/levels": {
      "get": {
        "description": "Get all 30 level definitions with XP thresholds, visual metadata, and benefits (v4.70).",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "levels": {
                          "items": {
                            "$ref": "#/components/schemas/LevelDefinition"
                          },
                          "type": "array"
                        },
                        "meta": {
                          "properties": {
                            "total": {
                              "example": 30,
                              "type": "integer"
                            }
                          },
                          "type": "object"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Level definitions"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get level definitions (レベル定義)",
        "tags": [
          "Gamification"
        ]
      }
    },
    "/gamification/definitions/xp-rewards": {
      "get": {
        "description": "Get all XP reward definitions with daily limits.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "meta": {
                          "properties": {
                            "total": {
                              "example": 18,
                              "type": "integer"
                            }
                          },
                          "type": "object"
                        },
                        "rewards": {
                          "items": {
                            "$ref": "#/components/schemas/XPRewardDefinition"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "XP reward definitions"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get XP reward definitions (XP報酬定義)",
        "tags": [
          "Gamification"
        ]
      }
    },
    "/gamification/goals/complete": {
      "post": {
        "description": "Mark a goal as completed and award XP.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/StartGoalRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/GoalOperationResponse"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Goal completed"
          },
          "400": {
            "description": "Goal not started"
          },
          "404": {
            "description": "Goal not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Complete a goal (ゴール完了)",
        "tags": [
          "Gamification"
        ]
      }
    },
    "/gamification/goals/start": {
      "post": {
        "description": "Start working on a goal. Validates prerequisites if any.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/StartGoalRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/GoalOperationResponse"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Goal started"
          },
          "400": {
            "description": "Prerequisites not met"
          },
          "404": {
            "description": "Goal not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Start a goal (ゴール開始)",
        "tags": [
          "Gamification"
        ]
      }
    },
    "/gamification/leaderboard": {
      "get": {
        "description": "Get company leaderboard with top users by XP.",
        "parameters": [
          {
            "in": "query",
            "name": "period",
            "schema": {
              "default": "weekly",
              "enum": [
                "weekly",
                "monthly",
                "all_time"
              ],
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "limit",
            "schema": {
              "default": 10,
              "maximum": 50,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/LeaderboardResponse"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Leaderboard"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get leaderboard (リーダーボード)",
        "tags": [
          "Gamification"
        ]
      }
    },
    "/gamification/login": {
      "post": {
        "description": "Record a login and update streaks. Called once per session.\n\n**Rate Limit:** 10 requests per 15 minutes\n\n**Streak Multipliers:**\n- 7+ days: 1.1x\n- 30+ days: 1.25x\n- 90+ days: 1.5x\n- 365+ days: 2.0x",
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/LoginResponse"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Login recorded"
          },
          "429": {
            "description": "Rate limit exceeded"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Record login (ログイン記録)",
        "tags": [
          "Gamification"
        ]
      }
    },
    "/gamification/progress": {
      "get": {
        "description": "Get complete gamification progress for the authenticated user including XP, level, achievements, goals, and streaks.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/GamificationProgress"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Progress data"
          },
          "401": {
            "description": "Not authenticated"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get gamification progress (進捗取得)",
        "tags": [
          "Gamification"
        ]
      }
    },
    "/gamification/time-saved": {
      "post": {
        "description": "Record time saved through automation. Mission-aligned metric.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/RecordTimeSavedRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "total_time_saved": {
                          "type": "integer"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Time saved recorded"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Record time saved (節約時間記録)",
        "tags": [
          "Gamification"
        ]
      }
    },
    "/gamification/xp": {
      "post": {
        "description": "Award XP for an event. Subject to daily limits per event type.\n\n**Rate Limit:** 100 requests per 15 minutes\n\n**Daily Limits:** Each event type has a maximum daily occurrence limit.",
        "requestBody": {
          "content": {
            "application/json": {
              "example": {
                "event_type": "document_create",
                "source_entity_id": "123e4567-e89b-12d3-a456-426614174000",
                "source_entity_type": "document"
              },
              "schema": {
                "$ref": "#/components/schemas/AwardXPRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/AwardXPResponse"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "XP awarded"
          },
          "429": {
            "description": "Rate limit exceeded"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Award XP (XP付与)",
        "tags": [
          "Gamification"
        ]
      }
    },
    "/gamification/xp/batch": {
      "post": {
        "description": "Award XP for multiple events in a single request.\n\n**Rate Limit:** 30 requests per 15 minutes (max 50 events per batch)",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/BatchAwardXPRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/BatchAwardXPResponse"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Batch processed"
          },
          "429": {
            "description": "Rate limit exceeded"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Batch award XP (バッチXP付与)",
        "tags": [
          "Gamification"
        ]
      }
    },
    "/general-ledger/bulk-post-drafts": {
      "post": {
        "description": "Post ALL draft journal entries to the general ledger at once. This implements the \"Accounting Hub\" pattern for real-time trial balance updates.\n\n## Accounting Hub Pattern (会計ハブパターン)\nModern accounting systems use event-driven architecture where:\n- Source transactions (expenses, invoices, bank feeds) create journal entries automatically\n- Journal entries are posted to the general ledger in bulk or automatically\n- Trial balance reflects real-time data without manual intervention\n\n## Use Cases\n- **\"Post All Drafts\" Button**: One-click posting of all pending journal entries\n- **Month-End Processing**: Batch post all draft entries at period close\n- **Data Migration**: Post imported journal entries in bulk\n- **Development/Testing**: Quickly populate general ledger for testing\n\n## Processing Logic\n1. Finds all draft journal entries for the authenticated user\n2. Posts each entry to the general ledger (creates ledger lines, updates balances)\n3. Skips entries with no journal entry lines\n4. Continues processing even if individual entries fail\n5. Returns detailed results for each entry\n\n## Data Flow\n```\nSource Documents → Journal Entries (draft) → [BULK POST] → General Ledger → Trial Balance\n```\n\n## Benefits\n- **Real-time Trial Balance**: Data appears immediately after posting\n- **Better UX**: No need to post entries one by one\n- **Audit Trail**: All posting operations are logged\n- **Error Handling**: Failed entries don't block successful ones\n\n## Authentication\nRequires valid Bearer token in Authorization header. Only posts entries belonging to the authenticated user.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "all_posted": {
                    "summary": "All entries posted successfully",
                    "value": {
                      "data": {
                        "failed": 0,
                        "posted": 7,
                        "results": [
                          {
                            "entryNumber": "JE-2024-001",
                            "journalId": "123e4567-e89b-12d3-a456-426614174001",
                            "status": "posted"
                          },
                          {
                            "entryNumber": "JE-2024-002",
                            "journalId": "123e4567-e89b-12d3-a456-426614174002",
                            "status": "posted"
                          }
                        ],
                        "skipped": 0,
                        "totalDrafts": 7
                      },
                      "message": "Bulk post completed: 7 posted, 0 failed, 0 skipped",
                      "statusCode": 200
                    }
                  },
                  "no_drafts": {
                    "summary": "No draft entries to post",
                    "value": {
                      "data": {
                        "failed": 0,
                        "posted": 0,
                        "results": [],
                        "skipped": 0,
                        "totalDrafts": 0
                      },
                      "message": "Bulk post completed: 0 posted, 0 failed, 0 skipped",
                      "statusCode": 200
                    }
                  },
                  "partial_success": {
                    "summary": "Some entries failed or skipped",
                    "value": {
                      "data": {
                        "failed": 1,
                        "posted": 5,
                        "results": [
                          {
                            "entryNumber": "JE-2024-001",
                            "journalId": "123e4567-e89b-12d3-a456-426614174001",
                            "status": "posted"
                          },
                          {
                            "entryNumber": "JE-2024-002",
                            "error": "Unbalanced entry",
                            "journalId": "123e4567-e89b-12d3-a456-426614174002",
                            "status": "failed"
                          },
                          {
                            "entryNumber": "JE-2024-003",
                            "error": "No journal entry lines",
                            "journalId": "123e4567-e89b-12d3-a456-426614174003",
                            "status": "skipped"
                          }
                        ],
                        "skipped": 1,
                        "totalDrafts": 7
                      },
                      "message": "Bulk post completed: 5 posted, 1 failed, 1 skipped",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/BulkPostResponse"
                }
              }
            },
            "description": "Bulk post completed (may include partial failures)"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Bulk post all draft journal entries to general ledger",
        "tags": [
          "General Ledger"
        ]
      }
    },
    "/general-ledger/ledger-summary": {
      "get": {
        "description": "Retrieve comprehensive general ledger summary with account balances and transaction analysis for specified period.\n\n## Ledger Summary Analysis (総勘定元帳集計)\nComprehensive ledger analysis providing:\n- **Account-wise Summaries**: Individual account analysis with opening/closing balances\n- **Transaction Aggregation**: Total debits, credits, and net changes for each account\n- **Running Balance Tracking**: Current balance for all accounts after transactions\n- **Period Analysis**: Financial activity within specified date range\n- **Balance Verification**: Validation of double-entry bookkeeping principles\n- **Account Classification**: Summary organized by account type and normal side\n\n## Financial Metrics\n- **Opening Balance (期首残高)**: Account balance at start of period. Balance-sheet accounts (asset /\n  liability / equity) carry every posted line before the period; revenue / expense accounts open at the\n  fiscal year to date (0 when the period starts on the FY start), since the ledger has no 損益振替; 利益剰余金\n  (sub_type retained_earnings) opens with the prior years' profit added, so the opening 借方 equals the 貸方.\n  A period that crosses a fiscal-year boundary keeps one continuous walk from that opening.\n- **Total Debits (借方合計)**: Sum of all debit transactions in period\n- **Total Credits (貸方合計)**: Sum of all credit transactions in period\n- **Closing Balance (期末残高)**: Account balance at end of period\n- **Net Change (純増減)**: Net increase or decrease during period\n- **Transaction Count**: Number of transactions affecting each account\n\n## Account Type Analysis\n- **Asset Accounts (資産)**: Cash, receivables, inventory, fixed assets\n- **Liability Accounts (負債)**: Payables, accrued expenses, loans\n- **Equity Accounts (純資産)**: Capital, retained earnings, reserves\n- **Revenue Accounts (収益)**: Sales, service income, other revenue\n- **Expense Accounts (費用)**: Operating expenses, cost of goods sold\n\n## Balance Calculation Logic\n- **Normal Side Respect**: Calculations based on account normal side (debit/credit)\n- **Asset/Expense Accounts**: Debit balance = Total Debits - Total Credits\n- **Liability/Equity/Revenue Accounts**: Credit balance = Total Credits - Total Debits\n- **Running Balance**: Walks from the opening balance above through the period\n- **Period Activity**: Isolated analysis of transactions within date range\n\n## Filtering Capabilities\n- **Date Range**: Filter transactions by entry date (startDate to endDate)\n- **Account Specific**: Optional filtering for single account analysis\n- **Active Accounts**: Only includes active accounts in summary\n- **User Scoped**: Results limited to user's accessible accounts and transactions\n\n## Japanese Accounting Integration\n- **Chart of Accounts**: Integration with Japanese standard account structure\n- **Fiscal Period**: Support for Japanese fiscal year periods (April-March)\n- **Account Naming**: Japanese account names and classifications\n- **Balance Sheet**: Account summaries structured for Japanese balance sheet\n- **Income Statement**: Revenue and expense account analysis for P&L\n\n## Use Cases\n- **Financial Reporting**: Generate data for financial statements and reports\n- **Account Analysis**: Detailed analysis of individual account activity\n- **Balance Sheet Preparation**: Account balances for balance sheet preparation\n- **Income Statement**: Revenue and expense summaries for P&L statements\n- **Audit Preparation**: Account summaries for audit working papers\n- **Management Reporting**: Internal financial analysis and reporting\n- **Cash Flow Analysis**: Cash and bank account balance tracking\n- **Budget Variance**: Compare actual balances with budgeted amounts\n\n## Period Flexibility\n- **Custom Periods**: Any date range within fiscal year\n- **Monthly Analysis**: Month-by-month account summaries\n- **Quarterly Reports**: Quarterly financial analysis\n- **Year-to-Date**: Cumulative analysis from fiscal year start\n- **Comparative Analysis**: Period-over-period comparison support\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Start date for ledger summary period in YYYYMMDD format",
            "example": 20240401,
            "in": "query",
            "name": "startDate",
            "required": true,
            "schema": {
              "maximum": 99991231,
              "minimum": 19000101,
              "type": "integer"
            }
          },
          {
            "description": "End date for ledger summary period in YYYYMMDD format",
            "example": 20241231,
            "in": "query",
            "name": "endDate",
            "required": true,
            "schema": {
              "maximum": 99991231,
              "minimum": 19000101,
              "type": "integer"
            }
          },
          {
            "description": "Optional account ID to filter summary for specific account",
            "example": "456e7890-f12a-34b5-c678-901234567890",
            "in": "query",
            "name": "accountId",
            "required": false,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "fiscal_year_summary": {
                    "summary": "Full fiscal year ledger summary",
                    "value": {
                      "data": {
                        "accounts": [
                          {
                            "account_code": "1001",
                            "account_id": "456e7890-f12a-34b5-c678-901234567890",
                            "account_name": "現金",
                            "account_type": "asset",
                            "closing_balance": 450000,
                            "net_change": 300000,
                            "normal_side": "debit",
                            "opening_balance": 150000,
                            "total_credits": 200000,
                            "total_debits": 500000,
                            "transaction_count": 15
                          },
                          {
                            "account_code": "4001",
                            "account_id": "123e4567-e89b-12d3-a456-426614174000",
                            "account_name": "売上高",
                            "account_type": "revenue",
                            "closing_balance": 1100000,
                            "net_change": 1100000,
                            "normal_side": "credit",
                            "opening_balance": 0,
                            "total_credits": 1100000,
                            "total_debits": 0,
                            "transaction_count": 25
                          }
                        ],
                        "end_date": 20241231,
                        "start_date": 20240401,
                        "total_accounts": 25,
                        "total_credit_amount": 5750000,
                        "total_debit_amount": 5750000,
                        "total_transactions": 150
                      },
                      "message": "Ledger summary retrieved successfully",
                      "statusCode": 200
                    }
                  },
                  "single_account_summary": {
                    "summary": "Single account ledger summary",
                    "value": {
                      "data": {
                        "accounts": [
                          {
                            "account_code": "1001",
                            "account_id": "456e7890-f12a-34b5-c678-901234567890",
                            "account_name": "現金",
                            "account_type": "asset",
                            "closing_balance": 450000,
                            "net_change": 300000,
                            "normal_side": "debit",
                            "opening_balance": 150000,
                            "total_credits": 200000,
                            "total_debits": 500000,
                            "transaction_count": 15
                          }
                        ],
                        "end_date": 20241231,
                        "start_date": 20240401,
                        "total_accounts": 1,
                        "total_credit_amount": 200000,
                        "total_debit_amount": 500000,
                        "total_transactions": 15
                      },
                      "message": "Ledger summary retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/LedgerSummaryResponse"
                }
              }
            },
            "description": "Ledger summary retrieved successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Invalid date format (use YYYYMMDD) or end date must be after start date",
                      "type": "string"
                    },
                    "fieldErrors": {
                      "additionalProperties": {
                        "items": {
                          "type": "string"
                        },
                        "type": "array"
                      },
                      "example": {
                        "endDate": [
                          "End date must be after start date"
                        ],
                        "startDate": [
                          "Start date must be in YYYYMMDD format"
                        ]
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid date parameters or date range"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "No accounts found for the specified criteria",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Account not found or no data for specified period"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get general ledger summary",
        "tags": [
          "General Ledger"
        ]
      }
    },
    "/general-ledger/post-journal-to-ledger/{journal_id}": {
      "post": {
        "description": "Post a draft journal entry to the general ledger, updating account balances and creating ledger lines.\n\n## Journal Posting Process (仕訳転記)\nComprehensive journal entry posting with:\n- **Status Validation**: Ensures journal entry is in draft status before posting\n- **Double-Entry Verification**: Validates that total debits equal total credits\n- **Ledger Line Creation**: Creates individual ledger lines for each journal entry line\n- **Running Balance Calculation**: Updates running balances for all affected accounts\n- **Status Update**: Changes journal entry status from draft to posted\n- **Audit Trail**: Records posting timestamp and user information\n\n## Balance Calculation Logic\n- **Normal Side Respect**: Calculates balances based on account normal side (debit/credit)\n- **Asset/Expense Accounts**: Debit increases balance, credit decreases balance\n- **Liability/Equity/Revenue Accounts**: Credit increases balance, debit decreases balance\n- **Running Balance**: Maintains cumulative balance after each transaction\n- **Previous Balance**: Retrieves and considers all previous transactions for accuracy\n\n## Account Integration\n- **Chart of Accounts**: Integration with Japanese standard chart of accounts\n- **Account Types**: Supports all account types (asset, liability, equity, revenue, expense)\n- **Account Validation**: Ensures all referenced accounts exist and are active\n- **Balance Tracking**: Maintains accurate running balances for each account\n- **Multi-Currency**: Supports foreign currency transactions with proper conversion\n\n## Japanese Accounting Standards\n- **Double-Entry Bookkeeping**: Strict adherence to double-entry principles (複式簿記)\n- **General Ledger Structure**: Follows Japanese general ledger format and conventions\n- **Fiscal Period Integration**: Proper handling of Japanese fiscal year periods\n- **Audit Requirements**: Maintains audit trail for statutory compliance\n- **Tax Compliance**: Ledger structure supports Japanese tax reporting requirements\n\n## Transaction Safety\n- **Atomic Operations**: All posting operations wrapped in database transactions\n- **Rollback Protection**: Automatic rollback if any part of posting fails\n- **Data Integrity**: Ensures ledger remains balanced and consistent\n- **Concurrency Control**: Handles concurrent posting operations safely\n- **Error Recovery**: Comprehensive error handling with detailed error messages\n\n## Use Cases\n- **Month-End Processing**: Post accumulated draft entries to general ledger\n- **Financial Reporting**: Create posted entries for financial statement preparation\n- **Audit Preparation**: Ensure all transactions are properly posted for audit\n- **Compliance**: Meet Japanese accounting standards for general ledger maintenance\n- **Cash Flow Management**: Track cash and bank account balances accurately\n- **Management Reporting**: Provide accurate account balances for internal reporting\n\n## Validation Rules\n- **Draft Status Required**: Only draft journal entries can be posted\n- **Balance Validation**: Total debits must equal total credits\n- **Account Existence**: All referenced accounts must exist and be active\n- **User Authorization**: User must have permission to post journal entries\n- **Date Validation**: Entry date must be valid and within allowed periods\n- **Amount Validation**: All amounts must be positive and properly formatted\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the draft journal entry to post to general ledger",
            "example": "789e0123-e45b-67c8-d901-234567890123",
            "in": "path",
            "name": "journal_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful_posting": {
                    "summary": "Successful journal posting",
                    "value": {
                      "data": {
                        "accounts_affected": [
                          {
                            "account_code": "1001",
                            "account_id": "456e7890-f12a-34b5-c678-901234567890",
                            "account_name": "現金",
                            "new_balance": 250000
                          },
                          {
                            "account_code": "4001",
                            "account_id": "123e4567-e89b-12d3-a456-426614174000",
                            "account_name": "売上高",
                            "new_balance": 1100000
                          }
                        ],
                        "entry_number": "JE-2024-001",
                        "journal_entry_id": "789e0123-e45b-67c8-d901-234567890123",
                        "ledger_lines_created": 2,
                        "posted_at": "2024-01-15T15:30:00.000Z",
                        "posted_by": "abc12345-def6-7890-ghij-klmnopqrstuv",
                        "status": "posted",
                        "total_amount": 110000
                      },
                      "message": "Journal posted to ledger successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/JournalPostingResponse"
                }
              }
            },
            "description": "Journal entry posted to general ledger successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "details": {
                      "properties": {
                        "balanceDifference": {
                          "example": 10000,
                          "type": "number"
                        },
                        "currentStatus": {
                          "example": "posted",
                          "type": "string"
                        },
                        "totalCredits": {
                          "example": 100000,
                          "type": "number"
                        },
                        "totalDebits": {
                          "example": 110000,
                          "type": "number"
                        }
                      },
                      "type": "object"
                    },
                    "error": {
                      "example": "Journal is not in draft status or is unbalanced",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid journal entry or posting validation errors"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Journal entry not found or access denied",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Journal entry not found or access denied"
          },
          "409": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Journal entry is already posted and cannot be posted again",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Journal entry already posted or in invalid state"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Post journal entry to general ledger",
        "tags": [
          "General Ledger"
        ]
      }
    },
    "/habit-reminders": {
      "get": {
        "description": "Missing month (≥ 3 of the 4 months before had 立替), 立替 / receipts on no 経費精算書 after 14 days, 合算支払明細書 or claims past their payday, and learned weekly / biweekly / monthly habits late by their tolerance. Dismissed and still-snoozed ones are left out. Not cached.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "items": {
                          "items": {
                            "$ref": "#/components/schemas/HabitReminder"
                          },
                          "type": "array"
                        },
                        "summary": {
                          "$ref": "#/components/schemas/HabitReminderSummary"
                        }
                      },
                      "required": [
                        "items",
                        "summary"
                      ],
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Reminders and the 精算 summary"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "The caller’s open 忘れていませんか reminders",
        "tags": [
          "Habit reminders"
        ]
      }
    },
    "/habit-reminders/dismiss": {
      "post": {
        "description": "The list is recomputed; only an id that is a reminder now is stored (else `applied: false`, `reason: stale`). Without snoozeDays the occurrence is hidden for good; a later occurrence has a new id and shows again.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/HabitReminderDismissRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/HabitReminderDismissResult"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Stored, or stale"
          },
          "400": {
            "description": "Validation error (RFC 9457)"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "「表示しない」 or 「後で」 on one reminder",
        "tags": [
          "Habit reminders"
        ]
      }
    },
    "/health": {
      "get": {
        "description": "\nQuick health check endpoint for load balancers and uptime monitoring.\n\n**Usage:**\n- Load balancer health probes\n- Uptime monitoring services\n- Simple availability checks\n\n**Response Codes:**\n- `200`: Service is healthy\n- `503`: Service is unhealthy (database down)\n\n**Note:** No authentication required.\n      ",
        "operationId": "quickHealthCheck",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "example": {
                  "requestId": "550e8400-e29b-41d4-a716-446655440000",
                  "status": "ok",
                  "timestamp": "2026-01-15T12:00:00.000Z"
                },
                "schema": {
                  "$ref": "#/components/schemas/QuickHealthResponse"
                }
              }
            },
            "description": "Service is healthy"
          },
          "503": {
            "content": {
              "application/json": {
                "example": {
                  "requestId": "550e8400-e29b-41d4-a716-446655440000",
                  "status": "error",
                  "timestamp": "2026-01-15T12:00:00.000Z"
                },
                "schema": {
                  "$ref": "#/components/schemas/QuickHealthResponse"
                }
              }
            },
            "description": "Service is unhealthy"
          }
        },
        "security": [],
        "summary": "Quick health check",
        "tags": [
          "Health"
        ]
      }
    },
    "/health/detailed": {
      "get": {
        "description": "\nComprehensive health check with all component status.\n\n**Includes:**\n- Database connectivity and latency\n- Circuit breaker status for all external services (OpenAI, Supabase, NTA API)\n- Memory usage and system metrics\n- Overall health assessment\n\n**Health States:**\n- `healthy`: All systems operational\n- `degraded`: Some services experiencing issues (e.g., circuit breaker open)\n- `unhealthy`: Critical systems down (e.g., database unavailable)\n\n**Circuit Breaker States:**\n- `CLOSED`: Service is healthy, requests allowed\n- `OPEN`: Service failing, requests blocked temporarily\n- `HALF_OPEN`: Testing recovery, limited requests allowed\n\n**Note:** No authentication required.\n      ",
        "operationId": "detailedHealthCheck",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "example": {
                  "checks": {
                    "failed": 0,
                    "passed": 1,
                    "total": 1
                  },
                  "components": {
                    "circuitBreakers": [
                      {
                        "failures": 0,
                        "lastFailure": null,
                        "name": "OpenAI",
                        "state": "CLOSED"
                      },
                      {
                        "failures": 0,
                        "lastFailure": null,
                        "name": "Supabase Storage",
                        "state": "CLOSED"
                      },
                      {
                        "failures": 0,
                        "lastFailure": null,
                        "name": "NTA Invoice API",
                        "state": "CLOSED"
                      },
                      {
                        "failures": 0,
                        "lastFailure": null,
                        "name": "External API",
                        "state": "CLOSED"
                      }
                    ],
                    "database": {
                      "lastCheck": "2026-01-15T12:00:00.000Z",
                      "latencyMs": 5,
                      "message": "Connected",
                      "status": "healthy"
                    }
                  },
                  "requestId": "550e8400-e29b-41d4-a716-446655440000",
                  "status": "healthy",
                  "system": {
                    "environment": "production",
                    "memoryUsage": {
                      "external": 12,
                      "heapTotal": 256,
                      "heapUsed": 128,
                      "percentUsed": 50,
                      "rss": 320
                    },
                    "nodeVersion": "v20.10.0",
                    "uptime": 86400
                  },
                  "timestamp": "2026-01-15T12:00:00.000Z",
                  "version": "4.24.0"
                },
                "schema": {
                  "$ref": "#/components/schemas/DetailedHealthResponse"
                }
              }
            },
            "description": "Detailed health status"
          },
          "503": {
            "content": {
              "application/json": {
                "example": {
                  "checks": {
                    "failed": 1,
                    "passed": 0,
                    "total": 1
                  },
                  "components": {
                    "circuitBreakers": [
                      {
                        "failures": 5,
                        "lastFailure": "2026-01-15T11:59:00.000Z",
                        "name": "OpenAI",
                        "state": "OPEN"
                      }
                    ],
                    "database": {
                      "lastCheck": "2026-01-15T12:00:00.000Z",
                      "latencyMs": 5000,
                      "message": "Connection refused",
                      "status": "unhealthy"
                    }
                  },
                  "status": "unhealthy",
                  "timestamp": "2026-01-15T12:00:00.000Z",
                  "version": "4.24.0"
                },
                "schema": {
                  "$ref": "#/components/schemas/DetailedHealthResponse"
                }
              }
            },
            "description": "System unhealthy"
          }
        },
        "security": [],
        "summary": "Detailed system health",
        "tags": [
          "Health"
        ]
      }
    },
    "/health/live": {
      "get": {
        "description": "\nKubernetes liveness probe endpoint.\n\n**Purpose:**\n- Verify the process is running\n- Kubernetes uses this to determine if pod should be restarted\n\n**Always returns 200** as long as the process is alive.\n\n**Note:** No authentication required.\n      ",
        "operationId": "livenessProbe",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "example": {
                  "alive": true,
                  "requestId": "550e8400-e29b-41d4-a716-446655440000",
                  "timestamp": "2026-01-15T12:00:00.000Z"
                },
                "schema": {
                  "$ref": "#/components/schemas/LivenessResponse"
                }
              }
            },
            "description": "Process is alive"
          }
        },
        "security": [],
        "summary": "Liveness probe (Kubernetes)",
        "tags": [
          "Health"
        ]
      }
    },
    "/health/ready": {
      "get": {
        "description": "\nKubernetes readiness probe endpoint.\n\n**Purpose:**\n- Verify the service can accept traffic\n- Kubernetes uses this to add/remove pod from service load balancer\n\n**Checks:**\n- Database connectivity\n- Critical circuit breakers not open\n\n**Returns:**\n- `200`: Ready to accept traffic\n- `503`: Not ready (e.g., database unavailable)\n\n**Note:** No authentication required.\n      ",
        "operationId": "readinessProbe",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "example": {
                  "ready": true,
                  "requestId": "550e8400-e29b-41d4-a716-446655440000",
                  "timestamp": "2026-01-15T12:00:00.000Z"
                },
                "schema": {
                  "$ref": "#/components/schemas/ReadinessResponse"
                }
              }
            },
            "description": "Ready to accept traffic"
          },
          "503": {
            "content": {
              "application/json": {
                "example": {
                  "ready": false,
                  "reason": "Database unavailable",
                  "requestId": "550e8400-e29b-41d4-a716-446655440000",
                  "timestamp": "2026-01-15T12:00:00.000Z"
                },
                "schema": {
                  "$ref": "#/components/schemas/ReadinessResponse"
                }
              }
            },
            "description": "Not ready"
          }
        },
        "security": [],
        "summary": "Readiness probe (Kubernetes)",
        "tags": [
          "Health"
        ]
      }
    },
    "/home/init": {
      "get": {
        "description": "Composite endpoint that fetches all data needed by the homepage in a single request, eliminating 8+ separate waterfall calls.\n\n**Parallelizes:**\n1. Accounting dock summary (仕訳・元帳・試算表) — `/api/accounting/dock-summary`\n2. Financial summary (試算表・P/L・B/S) — `/api/reports/financial-summary`\n3. Recent documents (最新の書類) — `/api/documents?page_size=8`\n4. Document statistics (書類タイプ別件数) — `/api/documents/statistics`\n5. Bank overview (銀行取引概要) — `/api/bank-statements/overview`\n\n**Performance:**\n| Metric | Before (waterfall) | After (parallel) |\n|--------|-------------------|-----------------|\n| Requests | 8+ sequential | 1 |\n| Latency | ~2500ms+ | ~800ms |\n\n**Fiscal year auto-resolution (v5.16):**\nWhen `start_date`/`end_date` are omitted, the backend auto-derives the user's fiscal year from:\n1. `fiscal_periods` table (ANNUAL period starting in current calendar year)\n2. `companies.fiscal_year_start/end` (MMDD config, handles cross-year FY)\n3. Calendar year Jan 1 – Dec 31 (ultimate fallback)\n\nThis eliminates the need for the frontend to make a double-call after loading company data.\n\n**Caching:** Results cached in memory for 2 minutes. Stale-while-revalidate: 60s. ETag supported.\n\n**Graceful degradation:** If any sub-query fails, the others still return data (failed query returns null).",
        "operationId": "getHomeInit",
        "parameters": [
          {
            "description": "Fiscal period start in YYYYMMDD format. When omitted, auto-derived from user fiscal year config.",
            "in": "query",
            "name": "start_date",
            "schema": {
              "example": 20260216,
              "type": "integer"
            }
          },
          {
            "description": "Fiscal period end in YYYYMMDD format. When omitted, auto-derived from user fiscal year config.",
            "in": "query",
            "name": "end_date",
            "schema": {
              "example": 20270215,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HomeInitResponse"
                }
              }
            },
            "description": "Homepage data fetched successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get all homepage data in one request",
        "tags": [
          "Home"
        ]
      }
    },
    "/inkans": {
      "get": {
        "description": "Retrieve all active inkans for the authenticated user.\n\n## Response\nReturns array of all active inkans ordered by type:\n1. Jitsuin (実印) - Corporate Registered Seal\n2. Ginkoin (銀行印) - Bank Seal\n3. Kakuin (角印) - Square Seal\n\n## Performance & Caching\n- **Batch signed URL generation**: Single API call for all inkans (optimized)\n- **Response caching**: 30 minutes (private, user-specific)\n- **ETag support**: Conditional requests with If-None-Match header\n- **stale-while-revalidate**: 5 minutes for background refresh\n\n### Cache Headers\n```\nCache-Control: private, max-age=1800, stale-while-revalidate=300\nETag: \"abc123...\"\nVary: Authorization\n```\n\n## Use Cases\n- Display user's registered seals in settings\n- Check which seal types are configured\n- Build inkan management interfaces\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "example": {
                  "data": [
                    {
                      "created_at": "2026-01-07T10:30:00.000Z",
                      "description": "Corporate registered seal",
                      "file_name": "jitsuin_seal.png",
                      "file_size": 102400,
                      "file_url": "https://supabase.co/storage/v1/object/public/inkans/user123/jitsuin_seal.png",
                      "id": "123e4567-e89b-12d3-a456-426614174000",
                      "inkan_type": "jitsuin",
                      "is_active": true,
                      "mime_type": "image/png",
                      "updated_at": "2026-01-07T10:30:00.000Z"
                    },
                    {
                      "created_at": "2026-01-07T10:35:00.000Z",
                      "description": "Square seal for invoices",
                      "file_name": "kakuin_seal.png",
                      "file_size": 85200,
                      "file_url": "https://supabase.co/storage/v1/object/public/inkans/user123/kakuin_seal.png",
                      "id": "456e7890-e12b-34d5-a678-901234567890",
                      "inkan_type": "kakuin",
                      "is_active": true,
                      "mime_type": "image/png",
                      "updated_at": "2026-01-07T10:35:00.000Z"
                    }
                  ],
                  "message": "Success",
                  "statusCode": 200
                },
                "schema": {
                  "$ref": "#/components/schemas/InkanListResponse"
                }
              }
            },
            "description": "Inkans retrieved successfully",
            "headers": {
              "Cache-Control": {
                "description": "Cache control directives",
                "schema": {
                  "example": "private, no-cache",
                  "type": "string"
                }
              },
              "ETag": {
                "description": "Entity tag for conditional requests",
                "schema": {
                  "example": "\"abc123def456\"",
                  "type": "string"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get all user inkans",
        "tags": [
          "Inkan"
        ]
      }
    },
    "/inkans/document": {
      "get": {
        "description": "Retrieve inkan URLs formatted for document template integration.\n\n## Response Format\nReturns an object with URLs for each inkan type, or null if not configured:\n- `jitsuin_url`: URL to registered seal image\n- `ginkoin_url`: URL to bank seal image\n- `kakuin_url`: URL to square seal image\n\n## Performance & Caching\n- **Response caching**: 30 minutes (private, user-specific)\n- **ETag support**: Conditional requests with If-None-Match header\n\n## Use Cases\n- Populate document templates with seal images\n- Generate PDF documents with proper seals\n- Preview documents with inkan placement\n\n## Integration\nUse these URLs directly in document templates:\n```json\n{\n  \"signature\": {\n    \"date\": 20260107,\n    \"name\": \"山田太郎\",\n    \"inkanImage\": \"{{jitsuin_url}}\"\n  }\n}\n```\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "example": {
                  "data": {
                    "ginkoin_url": "https://supabase.co/storage/v1/object/public/inkans/user123/ginkoin_seal.png",
                    "jitsuin_url": "https://supabase.co/storage/v1/object/public/inkans/user123/jitsuin_seal.png",
                    "kakuin_url": null
                  },
                  "message": "Success",
                  "statusCode": 200
                },
                "schema": {
                  "$ref": "#/components/schemas/InkansForDocumentResponse"
                }
              }
            },
            "description": "Inkans for document retrieved successfully",
            "headers": {
              "Cache-Control": {
                "description": "Cache control directives",
                "schema": {
                  "example": "private, no-cache",
                  "type": "string"
                }
              },
              "ETag": {
                "description": "Entity tag for conditional requests",
                "schema": {
                  "example": "\"abc123def456\"",
                  "type": "string"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get inkans for document templates",
        "tags": [
          "Inkan"
        ]
      }
    },
    "/inkans/history": {
      "get": {
        "description": "Retrieve complete change history for all inkans or a specific inkan.\n\n## Compliance Feature\nThis endpoint provides full audit trail for:\n- **Lost Inkan Investigation**: Track when inkans were uploaded, changed, or deleted\n- **Regulatory Compliance**: 電子帳簿保存法 compliant audit logging\n- **Security Audit**: Review all inkan operations with IP addresses and timestamps\n\n## History Information\nEach history entry includes:\n- **Version Number**: Sequential version for each change\n- **Action**: upload, update, delete\n- **Timestamp**: When the change occurred\n- **Reason**: Why the change was made\n- **Before/After Data**: Full data snapshot for comparison\n- **IP Address**: Client IP for security audit\n- **User Agent**: Browser/client information\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "history": {
                          "items": {
                            "properties": {
                              "action": {
                                "example": "inkan_upload",
                                "type": "string"
                              },
                              "changed_at": {
                                "format": "date-time",
                                "type": "string"
                              },
                              "data_after": {
                                "type": "object"
                              },
                              "data_before": {
                                "nullable": true,
                                "type": "object"
                              },
                              "reason": {
                                "example": "New 実印 uploaded",
                                "nullable": true,
                                "type": "string"
                              },
                              "version": {
                                "example": 1,
                                "type": "integer"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Success",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Inkan history retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get inkan change history (audit trail)",
        "tags": [
          "Inkan"
        ]
      }
    },
    "/inkans/history/{inkan_id}": {
      "get": {
        "description": "Retrieve change history for a specific inkan by its UUID.",
        "parameters": [
          {
            "description": "UUID of the inkan",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "in": "path",
            "name": "inkan_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "history": {
                          "items": {
                            "type": "object"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Inkan history retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get specific inkan history",
        "tags": [
          "Inkan"
        ]
      }
    },
    "/inkans/type/{inkan_type}": {
      "delete": {
        "description": "Delete inkan by its type (jitsuin, ginkoin, or kakuin).\n\n## Behavior\n- Deletes all inkans of the specified type for the user (including inactive ones)\n- Performs soft delete (marks as deleted)\n- Useful for clearing a specific seal type before uploading a new one\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Type of inkan to delete",
            "example": "kakuin",
            "in": "path",
            "name": "inkan_type",
            "required": true,
            "schema": {
              "enum": [
                "jitsuin",
                "ginkoin",
                "kakuin"
              ],
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "message": {
                      "example": "kakuin inkan deleted successfully",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Inkan deleted successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Invalid inkan type. Must be one of: jitsuin, ginkoin, kakuin",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid inkan type"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Delete inkan by type",
        "tags": [
          "Inkan"
        ]
      }
    },
    "/inkans/{inkan_id}": {
      "delete": {
        "description": "Delete a specific inkan by its UUID.\n\n## Behavior\n- Performs soft delete (marks as deleted, does not remove from storage)\n- The inkan will no longer appear in listings or document templates\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the inkan to delete",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "in": "path",
            "name": "inkan_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "message": {
                      "example": "Inkan deleted successfully",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Inkan deleted successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Delete inkan by ID",
        "tags": [
          "Inkan"
        ]
      },
      "put": {
        "description": "Update the description of an existing inkan.\n\n## Note\nThis endpoint only updates the description. To replace the inkan image, \nuse the POST endpoint with the inkan type.\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the inkan to update",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "in": "path",
            "name": "inkan_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "example": {
                "description": "Updated company seal - registered March 2026"
              },
              "schema": {
                "$ref": "#/components/schemas/UpdateInkanRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/InkanResponse"
                }
              }
            },
            "description": "Inkan updated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update inkan description",
        "tags": [
          "Inkan"
        ]
      }
    },
    "/inkans/{inkan_type}": {
      "get": {
        "description": "Retrieve a specific inkan by its type.\n\n## Performance & Caching\n- **Response caching**: 30 minutes (private, user-specific)\n- **ETag support**: Conditional requests with If-None-Match header\n\n## Inkan Types\n| Type | Description |\n|------|-------------|\n| `jitsuin` | Corporate Registered Seal (実印) |\n| `ginkoin` | Bank Seal (銀行印) |\n| `kakuin` | Square Seal (角印) |\n\n## Response\nReturns the active inkan of the specified type, or null if not configured.\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Type of inkan to retrieve",
            "example": "jitsuin",
            "in": "path",
            "name": "inkan_type",
            "required": true,
            "schema": {
              "enum": [
                "jitsuin",
                "ginkoin",
                "kakuin"
              ],
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/InkanResponse"
                }
              }
            },
            "description": "Inkan retrieved successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Invalid inkan type. Must be one of: jitsuin, ginkoin, kakuin",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid inkan type"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get inkan by type",
        "tags": [
          "Inkan"
        ]
      },
      "post": {
        "description": "Upload a new inkan image for the specified type.\n\n## Important Behavior\n- **Automatic Replacement**: If an inkan of the same type already exists, it will be deactivated and replaced.\n- **One Active Per Type**: Each user can have only one active inkan per type.\n- **Image Validation**: Only image files (JPEG, PNG, GIF, WebP, SVG) are accepted.\n- **Size Limit**: Maximum file size is 2MB.\n\n## Inkan Types\n| Type | Japanese | Usage |\n|------|----------|-------|\n| `jitsuin` | 実印 | Contracts, official documents |\n| `ginkoin` | 銀行印 | Banking, financial transactions |\n| `kakuin` | 角印 | Invoices, quotations, receipts |\n\n## File Requirements\n- **Formats**: JPEG, PNG, GIF, WebP, SVG\n- **Max Size**: 2MB\n- **Recommended**: PNG with transparency for best document integration\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Type of inkan to upload",
            "example": "jitsuin",
            "in": "path",
            "name": "inkan_type",
            "required": true,
            "schema": {
              "enum": [
                "jitsuin",
                "ginkoin",
                "kakuin"
              ],
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "multipart/form-data": {
              "schema": {
                "$ref": "#/components/schemas/UploadInkanRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/Inkan"
                    },
                    "message": {
                      "example": "jitsuin inkan uploaded successfully",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 201,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Inkan uploaded successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Invalid file type. Only image files (JPEG, PNG, GIF, WebP, SVG) are allowed for inkan.",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid request (bad file type, size, or inkan type)"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "413": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "File size exceeds maximum limit of 2MB",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "File size exceeds limit"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Upload inkan image",
        "tags": [
          "Inkan"
        ]
      }
    },
    "/integrations/batches": {
      "get": {
        "parameters": [
          {
            "in": "query",
            "name": "source",
            "schema": {
              "enum": [
                "tsumagoi",
                "yen_yen",
                "stripe"
              ],
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "status",
            "schema": {
              "enum": [
                "drafted",
                "approved",
                "skipped",
                "failed",
                "superseded"
              ],
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "page",
            "schema": {
              "default": 1,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "pageSize",
            "schema": {
              "default": 20,
              "maximum": 100,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "items": {
                        "$ref": "#/components/schemas/IntegrationBatch"
                      },
                      "type": "array"
                    },
                    "message": {
                      "type": "string"
                    },
                    "pagination": {
                      "$ref": "#/components/schemas/Pagination"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data",
                    "pagination"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Batches"
          },
          "400": {
            "description": "Validation error"
          },
          "401": {
            "description": "Unauthorized"
          },
          "403": {
            "description": "管理者権限が必要です"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "連携バッチ with draft line previews",
        "tags": [
          "Integrations"
        ]
      }
    },
    "/integrations/batches/approve-all": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "additionalProperties": false,
                "properties": {
                  "source": {
                    "enum": [
                      "tsumagoi",
                      "yen_yen",
                      "stripe"
                    ],
                    "type": "string"
                  }
                },
                "type": "object"
              }
            }
          },
          "required": false
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "additionalProperties": false,
                      "properties": {
                        "approved": {
                          "type": "integer"
                        },
                        "failed": {
                          "items": {
                            "additionalProperties": false,
                            "properties": {
                              "error": {
                                "type": "string"
                              },
                              "id": {
                                "format": "uuid",
                                "type": "string"
                              }
                            },
                            "required": [
                              "id",
                              "error"
                            ],
                            "type": "object"
                          },
                          "type": "array"
                        }
                      },
                      "required": [
                        "approved",
                        "failed"
                      ],
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Approved"
          },
          "401": {
            "description": "Unauthorized"
          },
          "403": {
            "description": "管理者権限が必要です"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Approve every drafted batch (oldest first; each runs its own period-lock check)",
        "tags": [
          "Integrations"
        ]
      }
    },
    "/integrations/batches/{id}/approve": {
      "post": {
        "description": "Refuses (400 ERR_10002) when an entry date is in a closed or posting-locked period (BE ADR-0012). Inside a 修正申告 send X-Filing-Amendment-Year and X-Filing-Change-Reason (FE ADR-0013). Applies the batch inventory plan and links a matched payout deposit.",
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "additionalProperties": false,
                      "properties": {
                        "id": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "posted": {
                          "type": "integer"
                        },
                        "status": {
                          "enum": [
                            "approved"
                          ],
                          "type": "string"
                        }
                      },
                      "required": [
                        "id",
                        "status",
                        "posted"
                      ],
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Approved"
          },
          "400": {
            "description": "Period locked"
          },
          "401": {
            "description": "Unauthorized"
          },
          "403": {
            "description": "管理者権限が必要です"
          },
          "404": {
            "description": "Batch not found"
          },
          "409": {
            "description": "Batch is not drafted"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Approve a batch: post its drafts through the ledger's posting path",
        "tags": [
          "Integrations"
        ]
      }
    },
    "/integrations/batches/{id}/retry": {
      "post": {
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "additionalProperties": false,
                      "properties": {
                        "error": {
                          "nullable": true,
                          "type": "string"
                        },
                        "id": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "status": {
                          "enum": [
                            "drafted",
                            "approved",
                            "skipped",
                            "failed",
                            "superseded"
                          ],
                          "type": "string"
                        }
                      },
                      "required": [
                        "id",
                        "status",
                        "error"
                      ],
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Retried"
          },
          "401": {
            "description": "Unauthorized"
          },
          "403": {
            "description": "管理者権限が必要です"
          },
          "404": {
            "description": "Batch not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Re-run a failed batch from its log row",
        "tags": [
          "Integrations"
        ]
      }
    },
    "/integrations/claim-duplicates": {
      "get": {
        "description": "status=open (default) is the owner's queue: undecided flags (open, resolving) plus decided ones whose held claim was not published.",
        "parameters": [
          {
            "in": "query",
            "name": "status",
            "required": false,
            "schema": {
              "default": "open",
              "enum": [
                "open",
                "resolving",
                "kept",
                "distinct",
                "voided",
                "closed",
                "all"
              ],
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "items": {
                        "$ref": "#/components/schemas/IntegrationClaimDuplicate"
                      },
                      "type": "array"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Reviews"
          },
          "400": {
            "description": "Validation error"
          },
          "401": {
            "description": "Unauthorized"
          },
          "403": {
            "description": "管理者権限が必要です"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "「重複の可能性」: integration 立替 claims that may pay for the same purchase as another integration’s",
        "tags": [
          "Integrations"
        ]
      }
    },
    "/integrations/claim-duplicates/scan": {
      "post": {
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "additionalProperties": false,
                      "properties": {
                        "flagged": {
                          "type": "integer"
                        },
                        "scanned": {
                          "type": "integer"
                        },
                        "truncated": {
                          "description": "Older claims, or claims past the cap, were not replayed",
                          "type": "boolean"
                        },
                        "windowDays": {
                          "type": "integer"
                        }
                      },
                      "required": [
                        "scanned",
                        "flagged",
                        "truncated",
                        "windowDays"
                      ],
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Scanned"
          },
          "401": {
            "description": "Unauthorized"
          },
          "403": {
            "description": "管理者権限が必要です"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Flag possible duplicates among claims raised before the guard (flags only; nothing voided or held)",
        "tags": [
          "Integrations"
        ]
      }
    },
    "/integrations/claim-duplicates/{id}/resolve": {
      "post": {
        "description": "keep_flagged: void the counterpart(s) (voidDocument reverses their 仕訳) and publish this claim. keep_counterparts: void this claim. distinct (別の支出): publish this claim as it is. A claim settled by a reimbursement transfer is never voided (409).",
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "additionalProperties": false,
                "properties": {
                  "decision": {
                    "enum": [
                      "keep_flagged",
                      "keep_counterparts",
                      "distinct"
                    ],
                    "type": "string"
                  }
                },
                "required": [
                  "decision"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "additionalProperties": false,
                      "properties": {
                        "id": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "status": {
                          "enum": [
                            "open",
                            "resolving",
                            "kept",
                            "distinct",
                            "voided",
                            "closed"
                          ],
                          "type": "string"
                        },
                        "voided": {
                          "items": {
                            "format": "uuid",
                            "type": "string"
                          },
                          "type": "array"
                        }
                      },
                      "required": [
                        "id",
                        "status",
                        "voided"
                      ],
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Resolved"
          },
          "401": {
            "description": "Unauthorized"
          },
          "403": {
            "description": "管理者権限が必要です"
          },
          "404": {
            "description": "No possible duplicate on this claim"
          },
          "409": {
            "description": "Already resolved, or a counterpart is settled / in a locked period"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Resolve a possible duplicate",
        "tags": [
          "Integrations"
        ]
      }
    },
    "/integrations/google-calendar/callback": {
      "get": {
        "parameters": [
          {
            "in": "query",
            "name": "code",
            "schema": {
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "state",
            "schema": {
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "error",
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "302": {
            "description": "Back to /settings?tab=calendar-sync&gcal=connected | calendar_deleted | error_denied | error_state | error_scope | error_failed"
          }
        },
        "summary": "Google OAuth redirect (public; the state token is the control)",
        "tags": [
          "Google Calendar"
        ]
      }
    },
    "/integrations/google-calendar/connect": {
      "post": {
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "additionalProperties": false,
                      "properties": {
                        "authorizationUrl": {
                          "format": "uri",
                          "type": "string"
                        }
                      },
                      "required": [
                        "authorizationUrl"
                      ],
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Consent URL"
          },
          "401": {
            "description": "Unauthorized"
          },
          "409": {
            "description": "Not connected, or the action does not apply in this state"
          },
          "503": {
            "description": "The Google OAuth client is not configured"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Start the Google consent (one-time state, 10 minutes)",
        "tags": [
          "Google Calendar"
        ]
      }
    },
    "/integrations/google-calendar/disconnect": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "additionalProperties": false,
                "properties": {
                  "deleteCalendar": {
                    "type": "boolean"
                  }
                },
                "type": "object"
              }
            }
          },
          "required": false
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/GoogleCalendarStatus"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Disconnected"
          },
          "400": {
            "description": "Validation error"
          },
          "401": {
            "description": "Unauthorized"
          },
          "409": {
            "description": "Not connected, or the action does not apply in this state"
          },
          "503": {
            "description": "The Google OAuth client is not configured"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Revoke and clear the tokens; the calendar stays unless deleteCalendar",
        "tags": [
          "Google Calendar"
        ]
      }
    },
    "/integrations/google-calendar/events/{id}/restore": {
      "post": {
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/GoogleCalendarStatus"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Restored"
          },
          "400": {
            "description": "Validation error"
          },
          "401": {
            "description": "Unauthorized"
          },
          "409": {
            "description": "Not connected, or the action does not apply in this state"
          },
          "503": {
            "description": "The Google OAuth client is not configured"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "再追加 an event the owner deleted in Google",
        "tags": [
          "Google Calendar"
        ]
      }
    },
    "/integrations/google-calendar/recreate-calendar": {
      "post": {
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/GoogleCalendarStatus"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Recreated"
          },
          "401": {
            "description": "Unauthorized"
          },
          "409": {
            "description": "Not connected, or the action does not apply in this state"
          },
          "503": {
            "description": "The Google OAuth client is not configured"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "カレンダーを作り直す (only after the owner deleted 「一人社長 期限」)",
        "tags": [
          "Google Calendar"
        ]
      }
    },
    "/integrations/google-calendar/settings": {
      "patch": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "additionalProperties": false,
                "properties": {
                  "categories": {
                    "additionalProperties": {
                      "type": "boolean"
                    },
                    "description": "Only the categories switched: national_tax, local_tax, social_labor, withholding_payroll, corporate_registry, other",
                    "type": "object"
                  },
                  "popupReminder": {
                    "type": "boolean"
                  },
                  "prepEvents": {
                    "type": "boolean"
                  }
                },
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/GoogleCalendarStatus"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Saved and synced"
          },
          "400": {
            "description": "Validation error"
          },
          "401": {
            "description": "Unauthorized"
          },
          "409": {
            "description": "Not connected, or the action does not apply in this state"
          },
          "503": {
            "description": "The Google OAuth client is not configured"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Categories, 準備開始 events, popup reminder",
        "tags": [
          "Google Calendar"
        ]
      }
    },
    "/integrations/google-calendar/status": {
      "get": {
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/GoogleCalendarStatus"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Status"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Connection, choices, removed events and 予定日",
        "tags": [
          "Google Calendar"
        ]
      }
    },
    "/integrations/google-calendar/sync": {
      "post": {
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/GoogleCalendarStatus"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Synced"
          },
          "401": {
            "description": "Unauthorized"
          },
          "409": {
            "description": "Not connected, or the action does not apply in this state"
          },
          "503": {
            "description": "The Google OAuth client is not configured"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "今すぐ同期: pull the owner’s edits, then write",
        "tags": [
          "Google Calendar"
        ]
      }
    },
    "/integrations/google-calendar/webhook": {
      "post": {
        "description": "Always 200. The incremental pull runs before the answer; an unknown or forged channel is ignored.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "additionalProperties": false,
                      "properties": {
                        "outcome": {
                          "enum": [
                            "ignored",
                            "sync",
                            "synced"
                          ],
                          "type": "string"
                        }
                      },
                      "required": [
                        "outcome"
                      ],
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Handled or ignored"
          }
        },
        "summary": "Google push notification (public; X-Goog-Channel-Token = HMAC of the channel id)",
        "tags": [
          "Google Calendar"
        ]
      }
    },
    "/integrations/google-drive/callback": {
      "get": {
        "parameters": [
          {
            "in": "query",
            "name": "code",
            "schema": {
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "state",
            "schema": {
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "error",
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "302": {
            "description": "Back to /settings?tab=drive-inbox&gdrive=connected | error_denied | error_state | error_scope | error_failed (error_state also when the browser-binding cookie is missing or does not match)"
          }
        },
        "summary": "Google OAuth redirect (public; the state token is the control)",
        "tags": [
          "Google Drive"
        ]
      }
    },
    "/integrations/google-drive/connect": {
      "post": {
        "description": "Also sets the HttpOnly cookie `sbc_gdrive_oauth` (SameSite=Lax, path /api/integrations/google-drive) that binds the state to this browser; the callback refuses a state without it.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "additionalProperties": false,
                      "properties": {
                        "authorizationUrl": {
                          "format": "uri",
                          "type": "string"
                        }
                      },
                      "required": [
                        "authorizationUrl"
                      ],
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Consent URL"
          },
          "401": {
            "description": "Unauthorized"
          },
          "403": {
            "description": "Google Drive refused access (sharing settings or the connected account)"
          },
          "409": {
            "description": "Not connected, folders not set, or the action does not apply in this state"
          },
          "503": {
            "description": "The Google OAuth client is not configured"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Start the Google consent (one-time state, 10 minutes)",
        "tags": [
          "Google Drive"
        ]
      }
    },
    "/integrations/google-drive/disconnect": {
      "post": {
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/GoogleDriveStatus"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Disconnected"
          },
          "401": {
            "description": "Unauthorized"
          },
          "403": {
            "description": "Google Drive refused access (sharing settings or the connected account)"
          },
          "409": {
            "description": "Not connected, folders not set, or the action does not apply in this state"
          },
          "503": {
            "description": "The Google OAuth client is not configured"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Revoke and clear the tokens; the folders and the inbox items are kept",
        "tags": [
          "Google Drive"
        ]
      }
    },
    "/integrations/google-drive/inbox": {
      "get": {
        "parameters": [
          {
            "in": "query",
            "name": "status",
            "schema": {
              "enum": [
                "new",
                "analyzed",
                "approved",
                "applied",
                "rejected",
                "failed"
              ],
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "page",
            "schema": {
              "default": 1,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "pageSize",
            "schema": {
              "default": 20,
              "maximum": 100,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "items": {
                        "$ref": "#/components/schemas/DriveInboxItem"
                      },
                      "type": "array"
                    },
                    "message": {
                      "type": "string"
                    },
                    "pagination": {
                      "$ref": "#/components/schemas/Pagination"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data",
                    "pagination"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Items"
          },
          "400": {
            "description": "Validation error"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Inbox items and what SBC proposes for each, newest first",
        "tags": [
          "Google Drive"
        ]
      }
    },
    "/integrations/google-drive/inbox/{id}/approve": {
      "post": {
        "description": "Explicit `bankStatementId` (a row, or null for 立替) is required unless the item is a clean card match (see DriveInboxItem.flags). The file must still be in the inbox. The 証憑 link is made, then under a per-owner lease the item and file are re-read, the undo record is written and the file is renamed + moved (a same-named file gets _2). On a failure the item stays `approved` with its error: approving again resumes it (it cannot change the decision), 却下 removes SBC’s link, and `complete-without-drive` ends it when the file is gone or was moved. An `applied` item answers as is.",
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "additionalProperties": false,
                "properties": {
                  "bankStatementId": {
                    "description": "null = no bank link",
                    "format": "uuid",
                    "nullable": true,
                    "type": "string"
                  },
                  "proposedFolderPath": {
                    "maxLength": 400,
                    "type": "string"
                  },
                  "proposedName": {
                    "maxLength": 200,
                    "type": "string"
                  }
                },
                "type": "object"
              }
            }
          },
          "required": false
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/DriveInboxItem"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Applied"
          },
          "400": {
            "description": "Validation error"
          },
          "401": {
            "description": "Unauthorized"
          },
          "403": {
            "description": "Google Drive refused access (sharing settings or the connected account)"
          },
          "404": {
            "description": "Item or bank row not found"
          },
          "409": {
            "description": "Not connected, folders not set, or the action does not apply in this state"
          },
          "423": {
            "description": "The bank row’s 仕訳 is in a filed 課税期間 (BE ADR-0011)"
          },
          "502": {
            "description": "Google Drive refused the change; approve again"
          },
          "503": {
            "description": "The Google OAuth client is not configured"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Approve: attach to the bank row as 証憑, then rename + move the file in Drive",
        "tags": [
          "Google Drive"
        ]
      }
    },
    "/integrations/google-drive/inbox/{id}/complete-without-drive": {
      "post": {
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/DriveInboxItem"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Applied without Drive"
          },
          "400": {
            "description": "Validation error"
          },
          "401": {
            "description": "Unauthorized"
          },
          "403": {
            "description": "Google Drive refused access (sharing settings or the connected account)"
          },
          "404": {
            "description": "Item not found"
          },
          "409": {
            "description": "Not connected, folders not set, or the action does not apply in this state"
          },
          "503": {
            "description": "The Google OAuth client is not configured"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Finish an approved item whose file is gone or moved, without changing Drive",
        "tags": [
          "Google Drive"
        ]
      }
    },
    "/integrations/google-drive/inbox/{id}/reanalyze": {
      "post": {
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/DriveInboxItem"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Queued"
          },
          "400": {
            "description": "Validation error"
          },
          "401": {
            "description": "Unauthorized"
          },
          "403": {
            "description": "Google Drive refused access (sharing settings or the connected account)"
          },
          "404": {
            "description": "Item not found"
          },
          "409": {
            "description": "Not connected, folders not set, or the action does not apply in this state"
          },
          "503": {
            "description": "The Google OAuth client is not configured"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Re-analyse: a failed or analysed item goes back to new with its tries reset",
        "tags": [
          "Google Drive"
        ]
      }
    },
    "/integrations/google-drive/inbox/{id}/reject": {
      "post": {
        "description": "An approved item is rejected under the folder lease after re-checking Drive; SBC’s own 証憑 link is removed.",
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/DriveInboxItem"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Rejected"
          },
          "400": {
            "description": "Validation error"
          },
          "401": {
            "description": "Unauthorized"
          },
          "403": {
            "description": "Google Drive refused access (sharing settings or the connected account)"
          },
          "404": {
            "description": "Item not found"
          },
          "409": {
            "description": "Not connected, folders not set, or the action does not apply in this state"
          },
          "503": {
            "description": "The Google OAuth client is not configured"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Reject: nothing changes in Drive and the file is not proposed again",
        "tags": [
          "Google Drive"
        ]
      }
    },
    "/integrations/google-drive/inbox/{id}/undo": {
      "post": {
        "description": "The item becomes analyzed again (flag undone). A file moved or renamed since is not chased (409).",
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/DriveInboxItem"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Undone"
          },
          "400": {
            "description": "Validation error"
          },
          "401": {
            "description": "Unauthorized"
          },
          "403": {
            "description": "Google Drive refused access (sharing settings or the connected account)"
          },
          "404": {
            "description": "Item not found"
          },
          "409": {
            "description": "Not connected, folders not set, or the action does not apply in this state"
          },
          "503": {
            "description": "The Google OAuth client is not configured"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "元に戻す: rename + move the file back from the undo record and remove SBC’s 証憑 link",
        "tags": [
          "Google Drive"
        ]
      }
    },
    "/integrations/google-drive/scan": {
      "post": {
        "description": "Answers quickly (CloudFront cuts at 30 s); the 15-minute run (GET /cron/drive-inbox-scan) analyses the new files, so `analyzed` here is 0 and `pending` says how many wait.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "additionalProperties": false,
                      "properties": {
                        "added": {
                          "type": "integer"
                        },
                        "analyzed": {
                          "type": "integer"
                        },
                        "failed": {
                          "type": "integer"
                        },
                        "found": {
                          "type": "integer"
                        },
                        "pending": {
                          "type": "integer"
                        }
                      },
                      "required": [
                        "found",
                        "added",
                        "analyzed",
                        "failed",
                        "pending"
                      ],
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Scanned"
          },
          "401": {
            "description": "Unauthorized"
          },
          "403": {
            "description": "Google Drive refused access (sharing settings or the connected account)"
          },
          "409": {
            "description": "Not connected, folders not set, or the action does not apply in this state"
          },
          "503": {
            "description": "The Google OAuth client is not configured"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "今すぐ確認: record new inbox files and refresh left_inbox / duplicate_in_inbox (no analysis)",
        "tags": [
          "Google Drive"
        ]
      }
    },
    "/integrations/google-drive/settings": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "additionalProperties": false,
                "description": "At least one. A folder URL is accepted and reduced to its id.",
                "properties": {
                  "archiveRootFolderId": {
                    "type": "string"
                  },
                  "inboxFolderId": {
                    "type": "string"
                  }
                },
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/GoogleDriveStatus"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Saved"
          },
          "400": {
            "description": "Validation error, or not a folder"
          },
          "401": {
            "description": "Unauthorized"
          },
          "403": {
            "description": "Google Drive refused access (sharing settings or the connected account)"
          },
          "404": {
            "description": "Folder not found or not shared with the account"
          },
          "409": {
            "description": "Not connected, folders not set, or the action does not apply in this state"
          },
          "503": {
            "description": "The Google OAuth client is not configured"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Set the inbox folder and the archive root (each checked to be a folder in Drive)",
        "tags": [
          "Google Drive"
        ]
      }
    },
    "/integrations/google-drive/status": {
      "get": {
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/GoogleDriveStatus"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Status"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Connection, folders and inbox counts",
        "tags": [
          "Google Drive"
        ]
      }
    },
    "/integrations/line/link-code": {
      "post": {
        "description": "Only its SHA-256 is stored. A new code replaces the previous one. 10 per 15 minutes per client.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "additionalProperties": false,
                      "properties": {
                        "addFriendUrl": {
                          "format": "uri",
                          "nullable": true,
                          "type": "string"
                        },
                        "code": {
                          "example": "SBC-7K3Q-X9P2",
                          "type": "string"
                        },
                        "expiresAt": {
                          "format": "date-time",
                          "type": "string"
                        }
                      },
                      "required": [
                        "code",
                        "expiresAt",
                        "addFriendUrl"
                      ],
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "The code"
          },
          "401": {
            "description": "Unauthorized"
          },
          "409": {
            "description": "LINE is not configured"
          },
          "429": {
            "description": "Too many codes"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "A one-time code (15 minutes) to send to SBC’s LINE account",
        "tags": [
          "LINE"
        ]
      }
    },
    "/integrations/line/status": {
      "get": {
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/LineLinkStatus"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Status"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Whether LINE is set up and linked",
        "tags": [
          "LINE"
        ]
      }
    },
    "/integrations/line/unlink": {
      "post": {
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/LineLinkStatus"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Status after unlinking"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Stop LINE reminders (forget the linked LINE user)",
        "tags": [
          "LINE"
        ]
      }
    },
    "/integrations/line/webhook": {
      "post": {
        "description": "follow → how to link; a message with a valid code → linked; unfollow → unlinked. An empty events list (LINE’s 検証) answers 200.",
        "parameters": [
          {
            "in": "header",
            "name": "X-Line-Signature",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "destination": {
                    "type": "string"
                  },
                  "events": {
                    "items": {
                      "type": "object"
                    },
                    "type": "array"
                  }
                },
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Handled"
          },
          "400": {
            "description": "Malformed body"
          },
          "401": {
            "description": "Missing or invalid signature"
          },
          "404": {
            "description": "LINE is not configured"
          }
        },
        "summary": "LINE platform events (public; X-Line-Signature = HMAC-SHA256 of the raw body)",
        "tags": [
          "LINE"
        ]
      }
    },
    "/integrations/sources": {
      "get": {
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "items": {
                        "$ref": "#/components/schemas/IntegrationSource"
                      },
                      "type": "array"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Sources"
          },
          "401": {
            "description": "Unauthorized"
          },
          "403": {
            "description": "管理者権限が必要です"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List pull sources (tokens never returned)",
        "tags": [
          "Integrations"
        ]
      }
    },
    "/integrations/sources/{source}": {
      "put": {
        "description": "Endpoint (https) and the shared x-kensaurus-integration-token value, stored AES-256-GCM encrypted. `token: null` removes it; omit to keep. `resetCursor` re-reads the source from the start (idempotent).",
        "parameters": [
          {
            "in": "path",
            "name": "source",
            "required": true,
            "schema": {
              "enum": [
                "tsumagoi",
                "yen_yen",
                "stripe"
              ],
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "additionalProperties": false,
                "properties": {
                  "claimMode": {
                    "enum": [
                      "claim",
                      "detail_only"
                    ],
                    "type": "string"
                  },
                  "enabled": {
                    "type": "boolean"
                  },
                  "endpoint": {
                    "format": "uri",
                    "nullable": true,
                    "type": "string"
                  },
                  "resetCursor": {
                    "type": "boolean"
                  },
                  "token": {
                    "maxLength": 500,
                    "minLength": 16,
                    "nullable": true,
                    "type": "string",
                    "writeOnly": true
                  }
                },
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/IntegrationSource"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Saved"
          },
          "400": {
            "description": "Validation error"
          },
          "401": {
            "description": "Unauthorized"
          },
          "403": {
            "description": "管理者権限が必要です"
          },
          "503": {
            "description": "BANK_TOKEN_ENCRYPTION_KEY not configured"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Configure a pull source",
        "tags": [
          "Integrations"
        ]
      }
    },
    "/integrations/status": {
      "get": {
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/IntegrationStatus"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Status"
          },
          "401": {
            "description": "Unauthorized"
          },
          "403": {
            "description": "管理者権限が必要です"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Integration status card: lag per source, drafts awaiting approval, unmatched payouts",
        "tags": [
          "Integrations"
        ]
      }
    },
    "/integrity-checks": {
      "post": {
        "description": "Execute comprehensive data integrity validation for financial data quality assurance.\n\n## Data Integrity Validation\nComprehensive integrity checking with:\n- **Multi-Type Validation**: Support for comprehensive, bank-only, journal-only, and period-close checks\n- **Period-Based Analysis**: Validate data within specific date ranges or fiscal years\n- **Violation Detection**: Identify and classify integrity violations by type and severity\n- **Performance Metrics**: Track execution time and calculate integrity rates\n- **Audit Trail**: Complete audit trail of all integrity checks and results\n\n## Check Types\n- **Comprehensive**: Complete validation of all financial data integrity\n- **Bank Only**: Focus on bank statement reconciliation and related data\n- **Journal Only**: Validate journal entries, evidence, and accounting relationships\n- **Period Close**: Specialized checks for period-end closing procedures\n\n## Validation Categories\n- **Duplicate Detection**: Identify duplicate transactions and entries\n- **Amount Verification**: Validate amount consistency across related records\n- **Date Consistency**: Check date alignment between related transactions\n- **Account Matching**: Verify account assignments and relationships\n- **Evidence Validation**: Ensure proper documentation and evidence links\n- **Balance Verification**: Validate balance calculations and reconciliations\n\n## Violation Classification\n- **Error Level**: Critical issues requiring immediate attention\n- **Warning Level**: Important issues that should be addressed\n- **Info Level**: Informational items for review and consideration\n\n## Performance Tracking\n- **Execution Metrics**: Track check execution time and performance\n- **Integrity Rates**: Calculate bank-to-journal and overall integrity rates\n- **Historical Trends**: Track integrity improvements over time\n- **Violation Statistics**: Comprehensive violation counting and categorization\n\n## Use Cases\n- **Data Quality Assurance**: Regular validation of financial data integrity\n- **Period-End Validation**: Comprehensive checks before period closing\n- **Reconciliation Verification**: Validate bank statement reconciliation accuracy\n- **Audit Preparation**: Ensure data integrity for audit readiness\n- **System Migration**: Validate data integrity after system changes\n\nBearer token authentication required.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/RunIntegrityCheckRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/IntegrityCheckResponse"
                }
              }
            },
            "description": "Integrity check completed successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Run data integrity check",
        "tags": [
          "Integrity Checks"
        ]
      }
    },
    "/integrity-checks/history": {
      "get": {
        "description": "Get paginated history of integrity checks for trend analysis and audit purposes.\n\n## Check History Management\nComprehensive history tracking with:\n- **Paginated Results**: Efficient pagination for large check histories\n- **Chronological Order**: Results ordered by execution time for trend analysis\n- **Filter Options**: Filter by check type, date range, and status\n- **Performance Tracking**: Track integrity improvements over time\n- **Audit Trail**: Complete audit trail of all integrity validation activities\n\n## Historical Analysis\n- **Trend Identification**: Identify data quality trends over time\n- **Performance Comparison**: Compare check execution times and results\n- **Violation Patterns**: Analyze violation patterns and resolution effectiveness\n- **Improvement Tracking**: Track data quality improvements and initiatives\n- **Compliance Documentation**: Document integrity validation for compliance\n\n## Pagination Features\n- **Configurable Page Size**: Adjustable page size (1-100 items, default 20)\n- **Navigation Support**: Previous/next page navigation information\n- **Total Counts**: Total item and page counts for UI development\n- **Performance Optimization**: Efficient pagination for large datasets\n\n## Use Cases\n- **Audit Documentation**: Provide comprehensive audit trail for regulators\n- **Trend Analysis**: Analyze data quality trends for continuous improvement\n- **Performance Monitoring**: Monitor check execution performance over time\n- **Compliance Reporting**: Generate compliance reports with historical data\n- **Quality Metrics**: Track data quality metrics and improvement initiatives\n\nBearer token authentication required.",
        "parameters": [
          {
            "description": "Number of items per page (1-100)",
            "example": 20,
            "in": "query",
            "name": "page_size",
            "required": false,
            "schema": {
              "default": 20,
              "maximum": 100,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "description": "Page number (1-based)",
            "example": 1,
            "in": "query",
            "name": "page",
            "required": false,
            "schema": {
              "default": 1,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/IntegrityCheckHistoryResponse"
                }
              }
            },
            "description": "Integrity check history retrieved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get integrity check history",
        "tags": [
          "Integrity Checks"
        ]
      }
    },
    "/integrity-checks/latest": {
      "get": {
        "description": "Get the most recent integrity check results for the authenticated user.\n\n## Latest Check Information\nComprehensive latest check data with:\n- **Recent Results**: Most recent integrity check execution results\n- **Violation Summary**: Summary of detected violations and their status\n- **Performance Metrics**: Execution time and integrity rate information\n- **Status Overview**: Overall data integrity status and trends\n- **Quick Assessment**: Rapid assessment of current data quality\n\n## Check Information\n- **Execution Details**: Check type, parameters, and execution metadata\n- **Violation Analysis**: Detailed violation breakdown by type and severity\n- **Integrity Metrics**: Bank-to-journal rate and overall integrity rate\n- **Performance Data**: Execution time and efficiency metrics\n- **Historical Context**: Comparison with previous check results\n\n## Use Cases\n- **Dashboard Display**: Show current integrity status on dashboards\n- **Quick Assessment**: Rapid assessment of data quality status\n- **Trend Analysis**: Compare with historical integrity check results\n- **Alert Generation**: Generate alerts based on integrity status changes\n- **Status Monitoring**: Monitor ongoing data quality improvements\n\n## Response Handling\n- **Data Available**: Returns complete check information when available\n- **No History**: Returns null data with appropriate message when no checks exist\n- **Error Handling**: Comprehensive error handling for various scenarios\n\nBearer token authentication required.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/IntegrityCheckResponse"
                }
              }
            },
            "description": "Latest integrity check retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get latest integrity check",
        "tags": [
          "Integrity Checks"
        ]
      }
    },
    "/integrity-checks/transactions/{transactionId}": {
      "get": {
        "description": "Get detailed integrity status and violation information for a specific transaction.\n\n## Transaction-Level Integrity\nGranular transaction integrity with:\n- **Integrity Score**: Numerical integrity score (0.0 to 1.0) for transaction quality assessment\n- **Violation Details**: Complete list of violations associated with the transaction\n- **Status Summary**: Summary of violation status and resolution progress\n- **Historical Tracking**: Track integrity improvements for specific transactions\n- **Quality Metrics**: Detailed quality metrics for transaction-level analysis\n\n## Integrity Assessment\n- **Score Calculation**: Comprehensive integrity score based on violation severity and count\n- **Violation Impact**: Assessment of violation impact on transaction integrity\n- **Resolution Progress**: Track violation resolution progress and outcomes\n- **Quality Trends**: Track transaction quality improvements over time\n- **Risk Assessment**: Assess transaction risk based on integrity violations\n\n## Use Cases\n- **Transaction Analysis**: Detailed analysis of specific transaction integrity\n- **Quality Assurance**: Ensure transaction quality before processing\n- **Risk Management**: Assess transaction risk based on integrity violations\n- **Audit Preparation**: Document transaction integrity for audit purposes\n- **Remediation Planning**: Plan remediation activities for specific transactions\n\nBearer token authentication required.",
        "parameters": [
          {
            "description": "Transaction ID to check integrity for",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "in": "path",
            "name": "transactionId",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/TransactionIntegrityResponse"
                }
              }
            },
            "description": "Transaction integrity status retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get transaction integrity status",
        "tags": [
          "Integrity Checks"
        ]
      }
    },
    "/integrity-checks/violations/{violationId}": {
      "patch": {
        "description": "Update the status and resolution information for a specific integrity violation.\n\n## Violation Resolution Workflow\nComprehensive violation management with:\n- **Status Progression**: Manage violation through resolution workflow (open → in_progress → resolved/ignored)\n- **Resolution Tracking**: Track resolution activities and outcomes\n- **Documentation**: Document resolution notes and ignored reasons\n- **Audit Trail**: Maintain complete audit trail of violation resolution activities\n- **Quality Assurance**: Ensure proper documentation for ignored violations\n\n## Status Workflow\n- **Open**: Initial violation status requiring attention\n- **In Progress**: Violation being actively worked on\n- **Resolved**: Violation successfully resolved with corrective action\n- **Ignored**: Violation acknowledged but intentionally not resolved\n\n## Documentation Requirements\n- **Resolution Notes**: Document resolution activities and outcomes\n- **Ignored Reasons**: Required documentation for ignored violations (minimum 5 characters)\n- **Audit Trail**: Maintain complete history of status changes and updates\n- **Quality Control**: Ensure proper documentation for compliance and audit\n\n## Use Cases\n- **Violation Resolution**: Track and document violation resolution activities\n- **Workflow Management**: Manage violation resolution workflow and priorities\n- **Audit Documentation**: Document violation resolution for audit and compliance\n- **Quality Improvement**: Track resolution effectiveness and improvement initiatives\n- **Exception Management**: Properly document and justify ignored violations\n\nBearer token authentication required.",
        "parameters": [
          {
            "description": "Violation ID to update",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "in": "path",
            "name": "violationId",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateViolationRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ViolationUpdateResponse"
                }
              }
            },
            "description": "Violation updated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update violation status",
        "tags": [
          "Integrity Checks"
        ]
      }
    },
    "/integrity-checks/{checkRunId}": {
      "get": {
        "description": "Get detailed information about a specific integrity check run.\n\n## Detailed Check Information\nComprehensive check details with:\n- **Complete Results**: Full check execution results and metadata\n- **Violation Details**: Detailed violation information with resolution status\n- **Performance Metrics**: Execution time, integrity rates, and efficiency data\n- **Parameter Information**: Check parameters and configuration details\n- **Historical Context**: Check execution context and environmental information\n\n## Violation Analysis\n- **Detailed Violations**: Complete violation list with descriptions and affected entities\n- **Severity Classification**: Violation severity levels and priority information\n- **Resolution Status**: Current resolution status and progress tracking\n- **Impact Assessment**: Assessment of violation impact on data integrity\n- **Resolution Guidance**: Guidance for violation resolution and remediation\n\n## Use Cases\n- **Detailed Analysis**: Comprehensive analysis of specific integrity check results\n- **Violation Investigation**: Investigate specific violations and their causes\n- **Resolution Planning**: Plan violation resolution activities and priorities\n- **Audit Documentation**: Document specific check results for audit purposes\n- **Performance Analysis**: Analyze check performance and optimization opportunities\n\nBearer token authentication required.",
        "parameters": [
          {
            "description": "Integrity check run ID",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "in": "path",
            "name": "checkRunId",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/IntegrityCheckResponse"
                }
              }
            },
            "description": "Integrity check retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get integrity check by ID",
        "tags": [
          "Integrity Checks"
        ]
      }
    },
    "/integrity-checks/{checkRunId}/rerun": {
      "post": {
        "description": "Rerun a previous integrity check with the same parameters.\n\n## Check Rerun Functionality\nEfficient check rerun with:\n- **Parameter Preservation**: Reuse original check parameters and configuration\n- **Updated Results**: Generate fresh results with current data state\n- **Performance Comparison**: Compare results with original check execution\n- **Trend Analysis**: Track data quality changes over time\n- **Validation Refresh**: Refresh validation results after data corrections\n\n## Rerun Benefits\n- **Consistency**: Maintain consistent check parameters for comparison\n- **Efficiency**: Avoid manual parameter re-entry for repeated checks\n- **Trend Tracking**: Track improvement trends after remediation activities\n- **Validation**: Validate that data corrections resolved identified issues\n- **Monitoring**: Regular monitoring with consistent check parameters\n\n## Use Cases\n- **Post-Remediation Validation**: Verify that violation fixes resolved issues\n- **Regular Monitoring**: Perform regular integrity checks with consistent parameters\n- **Trend Analysis**: Track data quality improvements over time\n- **Compliance Validation**: Regular compliance checks with standardized parameters\n- **Performance Monitoring**: Monitor data quality performance improvements\n\nBearer token authentication required.",
        "parameters": [
          {
            "description": "Original check run ID to rerun",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "in": "path",
            "name": "checkRunId",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/IntegrityCheckResponse"
                }
              }
            },
            "description": "Integrity check rerun completed successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Rerun integrity check",
        "tags": [
          "Integrity Checks"
        ]
      }
    },
    "/inventory": {
      "get": {
        "parameters": [
          {
            "in": "query",
            "name": "category",
            "schema": {
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "itemClass",
            "schema": {
              "$ref": "#/components/schemas/InventoryItemClass"
            }
          },
          {
            "in": "query",
            "name": "subcategory",
            "schema": {
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "expiringSoon",
            "schema": {
              "type": "boolean"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Paginated item list"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List inventory items",
        "tags": [
          "Inventory"
        ]
      },
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateInventoryItem"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "description": "Item created"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create inventory item",
        "tags": [
          "Inventory"
        ]
      }
    },
    "/inventory/from-expense": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateFromExpense"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "description": "Item and movement created"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create item + opening purchase_in movement from one expense row",
        "tags": [
          "Inventory"
        ]
      }
    },
    "/inventory/ingest-from-expenses": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/IngestFromExpenses"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Ingest result or preview"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Bulk classify expenses and create tracked_supply items (dryRun preview supported)",
        "tags": [
          "Inventory"
        ]
      }
    },
    "/inventory/rederive-names": {
      "post": {
        "responses": {
          "200": {
            "description": "Names updated"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Fix payee-named rows using extraction-sourced product names",
        "tags": [
          "Inventory"
        ]
      }
    },
    "/inventory/reparse-uploads": {
      "post": {
        "responses": {
          "200": {
            "description": "Reparse queued or completed"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Backfill Files Intelligence extraction for inventory-linked uploads",
        "tags": [
          "Inventory"
        ]
      }
    },
    "/inventory/valuation": {
      "get": {
        "description": "`year` is the FY label (the year the FY ends); the ANNUAL fiscal period ending in it sets `periodStart` / `asOf`, else the calendar year. Quantities replay movements up to `asOf`. last_purchase and moving_average are computed; other methods fall back to last_purchase with `valuationNote`.",
        "parameters": [
          {
            "in": "query",
            "name": "year",
            "schema": {
              "example": 2025,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Valuation totals and per-item breakdown (quantityAsOf, valuationUnitCost, valuationNote per item)"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Year-end inventory valuation (inventory_asset only)",
        "tags": [
          "Inventory"
        ]
      }
    },
    "/inventory/{inventory_item_id}": {
      "delete": {
        "parameters": [
          {
            "in": "path",
            "name": "inventory_item_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "204": {
            "description": "Deleted"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Soft-delete item",
        "tags": [
          "Inventory"
        ]
      },
      "get": {
        "parameters": [
          {
            "in": "path",
            "name": "inventory_item_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK"
          },
          "404": {
            "description": "Not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get item detail",
        "tags": [
          "Inventory"
        ]
      },
      "patch": {
        "parameters": [
          {
            "in": "path",
            "name": "inventory_item_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Updated"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update item",
        "tags": [
          "Inventory"
        ]
      }
    },
    "/inventory/{inventory_item_id}/disposal": {
      "post": {
        "parameters": [
          {
            "in": "path",
            "name": "inventory_item_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "201": {
            "description": "Disposal recorded"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Record disposal — optionally auto-generates 棚卸減耗損 journal entry",
        "tags": [
          "Inventory"
        ]
      }
    },
    "/inventory/{inventory_item_id}/movements": {
      "get": {
        "parameters": [
          {
            "in": "path",
            "name": "inventory_item_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Chronological movements"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Movement ledger (商品有高帳)",
        "tags": [
          "Inventory"
        ]
      },
      "post": {
        "parameters": [
          {
            "in": "path",
            "name": "inventory_item_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "201": {
            "description": "Movement recorded"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Record movement (purchase_in, sale_out, consume, adjustment, etc.)",
        "tags": [
          "Inventory"
        ]
      }
    },
    "/invoices/qualified/generate": {
      "post": {
        "description": "Generate a qualified invoice compliant with Japanese Invoice System requirements.\n\n## Qualified Invoice Generation (適格請求書生成)\nComprehensive invoice generation with:\n- **Legal Compliance**: Full compliance with Japanese Invoice System (適格請求書等保存方式)\n- **Registration Number**: Auto-insert issuer registration number (適格請求書発行事業者登録番号)\n- **Multi-Tax Rate Support**: Support for standard 10%, reduced 8%, and exempt 0% rates\n- **Tax Calculations**: Precise tax calculations by rate category\n- **Recipient Verification**: Optional recipient registration number verification\n- **Database Storage**: Optional saving to database with generated ID\n\n## Legal Requirements (法的要件)\nJapanese Invoice System compliance includes:\n- **Issuer Registration Number**: 発行事業者の登録番号 (T + 13 digits)\n- **Issuer Name**: 発行事業者の氏名又は名称\n- **Transaction Date**: 取引年月日\n- **Transaction Description**: 取引内容\n- **Tax Rate Totals**: 税率ごとの合計金額\n- **Tax Amounts**: 税率ごとの消費税額\n- **Recipient Name**: 書類の交付を受ける事業者の氏名又は名称\n\n## Tax Rate Categories\n- **Standard 10% (標準税率)**: Regular consumption tax rate for most goods and services\n- **Reduced 8% (軽減税率)**: Reduced rate for food, beverages, and newspapers\n- **Exempt 0% (非課税)**: Tax-exempt transactions (land sales, residential rent, insurance)\n\n## Invoice Features\n- **Automatic Numbering**: Generate sequential invoice numbers (INV-YYYYMM-0001)\n- **Tax Calculations**: Automatic tax calculation by rate category\n- **Bank Information**: Include payment bank details\n- **Notes Support**: Add custom notes and payment terms\n- **Verification**: Verify recipient registration numbers against government database\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/GenerateQualifiedInvoiceRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/QualifiedInvoiceResponse"
                }
              }
            },
            "description": "Qualified invoice generated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Generate qualified invoice (適格請求書生成)",
        "tags": [
          "Qualified Invoice"
        ]
      }
    },
    "/invoices/qualified/health": {
      "get": {
        "description": "Check the health and availability of the Qualified Invoice System API.\n\n## Health Check Features\nAPI health monitoring with:\n- **Service Status**: Verify API service availability\n- **Feature Overview**: List available qualified invoice features\n- **System Information**: Basic system health information\n- **Compliance Readiness**: Verify Invoice System compliance readiness\n\n## Available Features\n- **Qualified Invoice Generation**: Generate 適格請求書 with legal compliance\n- **Registration Number**: Auto-insert 適格請求書発行事業者登録番号\n- **Multi-Tax Rate Support**: Support for 10%/8%/0% tax rates\n- **Recipient Verification**: Verify recipient registration numbers\n- **HTML Generation**: Generate HTML for PDF export and printing\n\n## Use Cases\n- **System Monitoring**: Monitor API health and availability\n- **Feature Discovery**: Discover available invoice features\n- **Integration Testing**: Test API connectivity and basic functionality\n- **Service Verification**: Verify service is ready for invoice operations\n\nNo authentication required for health check.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/QualifiedInvoiceHealthResponse"
                }
              }
            },
            "description": "API health check successful"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "Health check for Qualified Invoice API",
        "tags": [
          "Qualified Invoice"
        ]
      }
    },
    "/invoices/qualified/preview": {
      "post": {
        "description": "Generate a preview of qualified invoice without saving to database.\n\n## Invoice Preview (適格請求書プレビュー)\nGenerate invoice preview with:\n- **No Database Storage**: Generate invoice without saving to database\n- **Full Invoice Data**: Complete invoice data structure for preview\n- **HTML Generation**: Generate HTML for immediate preview\n- **Tax Calculations**: Complete tax calculations and summaries\n- **Verification**: Optional recipient verification for accuracy\n- **Real-Time Preview**: Immediate preview generation for UI display\n\n## Preview Features\n- **Complete Invoice**: Full invoice structure with all required fields\n- **Tax Summary**: Detailed tax breakdown by rate category\n- **HTML Output**: Professional HTML layout for preview display\n- **Styling**: Japanese business invoice styling and formatting\n- **Responsive Design**: Mobile and desktop-friendly preview\n- **Print Ready**: HTML optimized for printing and PDF conversion\n\n## Use Cases\n- **UI Preview**: Display invoice preview in user interface\n- **Validation**: Validate invoice data before final generation\n- **Design Review**: Review invoice layout and formatting\n- **Client Approval**: Show invoice to client before issuing\n- **Testing**: Test invoice generation without database impact\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/GenerateQualifiedInvoiceRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/QualifiedInvoicePreviewResponse"
                }
              }
            },
            "description": "Invoice preview generated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Preview qualified invoice (適格請求書プレビュー)",
        "tags": [
          "Qualified Invoice"
        ]
      }
    },
    "/invoices/qualified/reference/tax-rates": {
      "get": {
        "description": "Get reference information for Japanese consumption tax rate categories.\n\n## Tax Rate Reference (税率区分参照)\nComprehensive tax rate information with:\n- **Rate Categories**: All available tax rate categories with details\n- **Rate Percentages**: Current tax rates for each category\n- **Usage Examples**: Examples of goods/services for each rate\n- **Legal Descriptions**: Official descriptions for each tax category\n- **Implementation Guide**: Guidance for proper tax rate application\n\n## Tax Rate Categories\n- **Standard 10% (標準税率)**: \n  - Rate: 10%\n  - Description: 通常の消費税率\n  - Examples: コンサルティング費用, ソフトウェア開発, 事務用品\n- **Reduced 8% (軽減税率)**:\n  - Rate: 8%\n  - Description: 飲食料品・新聞等に適用\n  - Examples: お弁当, 飲料水, 食品原材料\n- **Exempt 0% (非課税)**:\n  - Rate: 0%\n  - Description: 消費税非課税取引\n  - Examples: 土地の売買, 住宅の賃貸, 保険料\n\n## Reference Information\n- **Category Values**: System values for API usage\n- **Display Labels**: Japanese labels for user interface\n- **Rate Percentages**: Current tax rates\n- **Descriptions**: Detailed explanations for each category\n- **Examples**: Real-world examples for each tax rate\n\n## Use Cases\n- **UI Development**: Populate tax rate dropdowns and forms\n- **Validation**: Validate tax rate selections\n- **Documentation**: Reference for tax rate implementation\n- **Training**: Educational information about Japanese tax rates\n- **Integration**: Reference for third-party integrations\n\nNo authentication required for reference data.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/TaxRateReferenceResponse"
                }
              }
            },
            "description": "Tax rate reference retrieved successfully"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "Get tax rate categories reference (税率区分参照)",
        "tags": [
          "Qualified Invoice"
        ]
      }
    },
    "/invoices/qualified/{id}": {
      "get": {
        "description": "Retrieve a specific qualified invoice by its ID.\n\n## Invoice Retrieval (適格請求書取得)\nRetrieve saved invoice with:\n- **Complete Data**: Full invoice data structure with all fields\n- **Tax Information**: Complete tax calculations and summaries\n- **Verification Status**: Recipient verification status and date\n- **Bank Information**: Payment bank details if included\n- **Notes**: All notes and additional information\n- **Audit Trail**: Creation and modification information\n\n## Retrieved Information\n- **Invoice Details**: Complete invoice number, dates, and amounts\n- **Issuer Information**: Company details and registration number\n- **Recipient Information**: Client details and verification status\n- **Item Breakdown**: Detailed item list with tax calculations\n- **Tax Summary**: Tax breakdown by rate category\n- **Payment Information**: Bank details and payment terms\n\n## Use Cases\n- **Invoice Display**: Display saved invoice for review\n- **PDF Generation**: Retrieve data for PDF generation\n- **Audit Trail**: Review invoice history and details\n- **Reprint**: Reprint previously generated invoices\n- **Reference**: Use as reference for similar invoices\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Invoice ID",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/QualifiedInvoiceGetResponse"
                }
              }
            },
            "description": "Invoice retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "message": {
                      "example": "適格請求書が見つかりません",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invoice not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get qualified invoice by ID (適格請求書取得)",
        "tags": [
          "Qualified Invoice"
        ]
      }
    },
    "/invoices/qualified/{id}/html": {
      "get": {
        "description": "Generate HTML representation of qualified invoice for PDF conversion or printing.\n\n## HTML Generation (HTML生成)\nProfessional HTML generation with:\n- **Japanese Layout**: Professional Japanese business invoice layout\n- **Print Optimization**: Optimized for printing and PDF conversion\n- **Responsive Design**: Adapts to different page sizes and formats\n- **Professional Styling**: Clean, professional appearance with proper typography\n- **Tax Breakdown**: Clear tax summary by rate category\n- **Legal Compliance**: Includes all required legal elements\n\n## HTML Features\n- **Japanese Typography**: Proper Japanese font selection and sizing\n- **Business Format**: Standard Japanese business invoice format\n- **Tax Indicators**: Clear indicators for reduced tax rate items (※)\n- **Bank Information**: Formatted bank details for payments\n- **Notes Section**: Properly formatted notes and terms\n- **Registration Number**: Prominent display of registration number\n\n## Styling Elements\n- **Header Design**: Professional header with company information\n- **Table Layout**: Clean table layout for items and calculations\n- **Tax Summary**: Detailed tax breakdown table\n- **Footer Information**: Legal compliance and system information\n- **Print Styles**: CSS optimized for printing and PDF generation\n\n## Use Cases\n- **PDF Generation**: Convert HTML to PDF for official invoices\n- **Email Attachments**: Generate HTML for email invoice delivery\n- **Print Preview**: Display print-ready invoice in browser\n- **Archive**: Store HTML version for record keeping\n- **Integration**: Integrate with third-party PDF services\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Invoice ID",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "text/html": {
                "schema": {
                  "description": "HTML content for PDF conversion",
                  "example": "<!DOCTYPE html><html lang=\"ja\"><head><title>適格請求書 INV-202403-0001</title>...",
                  "type": "string"
                }
              }
            },
            "description": "HTML generated successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "message": {
                      "example": "適格請求書が見つかりません",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invoice not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get invoice HTML for PDF conversion (HTML取得)",
        "tags": [
          "Qualified Invoice"
        ]
      }
    },
    "/journal-entries": {
      "get": {
        "description": "Retrieve journal entries with comprehensive filtering and pagination for Japanese accounting management.\n\n## Journal Entry Listing\nReturns paginated list of journal entries with:\n- **Complete Entry Data**: Full journal entries with all line items\n- **Double-Entry Validation**: Verified debit/credit balance for each entry\n- **Source Tracking**: Origin of each journal entry (manual, document-generated, etc.)\n- **Status Management**: Draft, posted, and reversed entry tracking\n- **Financial Integrity**: Validated entries with proper accounting structure\n\n## Filtering Options\n- **Date Range**: Filter by entry date (start_date, end_date in YYYYMMDD)\n- **Status Filter**: Filter by entry status (draft, posted, reversed)\n- **Source Type**: Filter by journal entry source (manual, sales_invoice, etc.)\n- **Pagination**: Page-based navigation with configurable page size\n\n## Source Types (仕訳元区分)\n- **Manual (手動)**: Manually created journal entries\n- **Sales Invoice (売上請求書)**: Generated from sales invoices\n- **Expense Claim (経費精算)**: Generated from expense claims\n- **Purchase Invoice (仕入請求書)**: Generated from purchase invoices\n- **Bank Feed (銀行取引)**: Generated from bank transaction feeds\n- **Opening Balance (期首残高)**: Fiscal year opening balance entries\n- **Fixed Asset (固定資産)**: Asset acquisition and depreciation entries\n\n## Entry Status Workflow\n- **Draft (下書き)**: Entries being prepared, not yet posted\n- **Posted (転記済み)**: Finalized entries affecting account balances\n- **Reversed (取消済み)**: Cancelled entries with reversal documentation\n\n## Pagination Features\n- **Page Size**: Configurable entries per page (default: 20)\n- **Page Number**: Current page for navigation\n- **Total Count**: Complete count of matching entries\n- **Navigation**: Previous/next page information\n\n## Use Cases\n- **General Ledger**: Display journal entries for accounting review\n- **Audit Trail**: Track all financial transactions and adjustments\n- **Financial Analysis**: Review entries by source type and date range\n- **Data Validation**: Monitor entry status and integrity\n- **Reporting**: Extract entries for financial reports and analysis\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Number of entries per page",
            "example": 20,
            "in": "query",
            "name": "page_size",
            "required": false,
            "schema": {
              "default": 20,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "description": "Page number for pagination",
            "example": 1,
            "in": "query",
            "name": "page_number",
            "required": false,
            "schema": {
              "default": 1,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "description": "Start date filter in YYYYMMDD format",
            "example": 20240101,
            "in": "query",
            "name": "start_date",
            "required": false,
            "schema": {
              "maximum": 99991231,
              "minimum": 19000101,
              "type": "integer"
            }
          },
          {
            "description": "End date filter in YYYYMMDD format",
            "example": 20241231,
            "in": "query",
            "name": "end_date",
            "required": false,
            "schema": {
              "maximum": 99991231,
              "minimum": 19000101,
              "type": "integer"
            }
          },
          {
            "description": "Filter by journal entry status",
            "example": "posted",
            "in": "query",
            "name": "status",
            "required": false,
            "schema": {
              "enum": [
                "draft",
                "posted",
                "reversed"
              ],
              "type": "string"
            }
          },
          {
            "description": "Filter by journal entry source type",
            "example": "sales_invoice",
            "in": "query",
            "name": "source_type",
            "required": false,
            "schema": {
              "enum": [
                "manual",
                "expense_claim",
                "sales_invoice",
                "purchase_invoice",
                "bank_feed",
                "card_statement",
                "payroll",
                "fixed_asset",
                "depreciation",
                "opening_balance",
                "adjustment",
                "reversal"
              ],
              "type": "string"
            }
          },
          {
            "description": "BL-1177: add each entry's `evidenceStatus` (証憑 coverage by the credit engine's evidence rule). Costs one batched read over the page.",
            "example": true,
            "in": "query",
            "name": "include_evidence",
            "required": false,
            "schema": {
              "default": false,
              "type": "boolean"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/JournalListResponse"
                }
              }
            },
            "description": "Journal entries retrieved successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Invalid date format or status value",
                      "type": "string"
                    },
                    "fieldErrors": {
                      "additionalProperties": {
                        "items": {
                          "type": "string"
                        },
                        "type": "array"
                      },
                      "example": {
                        "status": [
                          "Status must be draft, posted, or reversed"
                        ]
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid query parameters"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List journal entries with filtering",
        "tags": [
          "Journal Entries"
        ]
      }
    },
    "/journal-entries/draft/bulk": {
      "post": {
        "description": "Generate draft journal entries for multiple documents simultaneously with batch processing efficiency.\n\n## Bulk Journal Generation\nProcesses multiple documents efficiently:\n- **Batch Processing**: Generate entries for multiple documents in single operation\n- **Performance Optimization**: Efficient database operations for large batches\n- **Individual Results**: Success/failure status for each document\n- **Transaction Safety**: Atomic operations ensure data consistency\n- **Error Isolation**: Individual document failures don't affect batch success\n\n## Batch Processing Benefits\n- **Efficiency**: Process multiple documents simultaneously\n- **Consistency**: Uniform journal generation rules across all documents\n- **Performance**: Optimized database operations for bulk processing\n- **Error Handling**: Detailed error reporting for each document\n- **Progress Tracking**: Batch processing progress and completion status\n\n## Document Validation\nEach document in batch validated for:\n- **Document Type**: Must be supported document type for journal generation\n- **Data Completeness**: Sufficient financial data for journal creation\n- **User Access**: User must have access to all documents in batch\n- **Processing Status**: Documents must be in appropriate status for processing\n- **Duplicate Prevention**: Prevents duplicate journal entries for same document\n\n## Use Cases\n- **Month-End Processing**: Generate entries for all month-end documents\n- **Batch Import**: Process imported documents in bulk\n- **Workflow Automation**: Automated journal generation for document workflows\n- **Performance**: Efficient processing of large document volumes\n- **Data Migration**: Bulk journal generation during system migrations\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "monthly_processing": {
                  "summary": "Monthly document processing",
                  "value": {
                    "document_ids": [
                      "123e4567-e89b-12d3-a456-426614174000",
                      "456e7890-f12a-34b5-c678-901234567890",
                      "789e0123-e45b-67c8-d901-234567890123",
                      "abc12345-def6-7890-ghij-klmnopqrstuv"
                    ]
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/BulkGenerateRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "failureCount": {
                          "example": 1,
                          "type": "integer"
                        },
                        "results": {
                          "items": {
                            "properties": {
                              "documentId": {
                                "format": "uuid",
                                "type": "string"
                              },
                              "error": {
                                "type": "string"
                              },
                              "journalEntryId": {
                                "format": "uuid",
                                "type": "string"
                              },
                              "success": {
                                "type": "boolean"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        },
                        "successCount": {
                          "example": 3,
                          "type": "integer"
                        },
                        "totalDocuments": {
                          "example": 4,
                          "type": "integer"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Bulk journal generation completed",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Bulk journal generation completed"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "No valid documents provided for processing",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid request or no valid documents provided"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Bulk generate draft journal entries",
        "tags": [
          "Journal Entries"
        ]
      }
    },
    "/journal-entries/draft/generate/{document_id}": {
      "post": {
        "description": "Generate draft journal entries automatically from a business document with Japanese accounting rules.\n\n## Automatic Journal Generation\nCreates journal entries from business documents:\n- **Document Analysis**: Analyzes document content and financial data\n- **Account Mapping**: Maps document items to appropriate chart of accounts\n- **Double-Entry Creation**: Generates balanced debit and credit entries\n- **Japanese Standards**: Follows Japanese accounting principles and practices\n- **Draft Status**: Creates entries in draft status for review before posting\n\n## Supported Document Types\n- **Sales Invoices**: Revenue recognition and receivables entries\n- **Purchase Invoices**: Expense recognition and payables entries\n- **Expense Claims**: Employee expense and reimbursement entries\n- **Fixed Assets**: Asset acquisition and depreciation entries\n- **Bank Transactions**: Cash and bank account entries\n- **Payment Documents**: Payment processing and cash flow entries\n\n## Journal Entry Generation Rules\n- **Revenue Recognition**: Sales invoices generate revenue and receivables entries\n- **Expense Recognition**: Purchase invoices generate expense and payables entries\n- **Cash Transactions**: Bank documents generate cash and corresponding entries\n- **Tax Handling**: Automatic consumption tax (消費税) calculation and entries\n- **Multi-Currency**: Foreign currency transactions with exchange rate handling\n\n## Japanese Accounting Integration\n- **Chart of Accounts**: Uses Japanese standard account codes and names\n- **Tax Compliance**: Consumption tax entries per Japanese tax law\n- **Fiscal Period**: Entries dated according to Japanese fiscal calendar\n- **Audit Trail**: Complete documentation linking entries to source documents\n\n## Validation and Review\n- **Balance Validation**: Ensures total debits equal total credits\n- **Account Validation**: Verifies all accounts exist and are active\n- **Amount Validation**: Validates financial amounts and calculations\n- **Draft Review**: Entries created in draft status for user review\n- **Error Handling**: Detailed error reporting for generation failures\n\n## Use Cases\n- **Document Processing**: Automate journal entry creation from business documents\n- **Workflow Automation**: Streamline accounting workflow with automatic generation\n- **Error Reduction**: Reduce manual entry errors with automated generation\n- **Audit Trail**: Maintain clear link between documents and journal entries\n- **Efficiency**: Speed up accounting processes with automation\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the document to generate journal entries from",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/JournalEntryResponse"
                }
              }
            },
            "description": "Draft journal entries generated successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Document contains insufficient data for journal generation",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid document or generation errors"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Document not found or access denied",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Document not found or access denied"
          },
          "409": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetails"
                }
              }
            },
            "description": "The 立替経費申請 rows cannot be posted (data.reason = CLAIM_LINES_NOT_POSTABLE; detail names each row and how to fix it), or a company-card line is unresolved"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Generate draft journal entries from document",
        "tags": [
          "Journal Entries"
        ]
      }
    },
    "/journal-entries/health-check": {
      "get": {
        "description": "Perform comprehensive data integrity analysis for journal entries and accounting data.\n\n## Data Integrity Analysis\nComprehensive health check covering:\n- **Orphan Entries**: Journal entries without corresponding line items\n- **Unbalanced Entries**: Entries where total debits ≠ total credits\n- **Missing Documents**: Entries with invalid or missing reference documents\n- **Account Validation**: Entries referencing non-existent accounts\n- **Health Score**: Overall data integrity score (0-100)\n\n## Integrity Metrics\n- **Orphan Detection**: Identifies entries without proper line item structure\n- **Balance Validation**: Verifies double-entry bookkeeping principles\n- **Reference Integrity**: Validates document and account references\n- **Data Consistency**: Checks for data anomalies and inconsistencies\n- **Performance Impact**: Identifies entries affecting system performance\n\n## Health Score Calculation\nBased on multiple factors:\n- **Entry Completeness**: Percentage of complete, valid entries\n- **Balance Accuracy**: Percentage of properly balanced entries\n- **Reference Integrity**: Percentage of entries with valid references\n- **Data Quality**: Overall data quality and consistency metrics\n\n## Recommendations Engine\nProvides actionable recommendations:\n- **Cleanup Actions**: Specific steps to improve data integrity\n- **Maintenance Tasks**: Regular maintenance recommendations\n- **Performance Optimization**: Suggestions for system performance improvement\n- **Compliance**: Recommendations for audit and compliance readiness\n\n## Use Cases\n- **System Monitoring**: Regular health checks for accounting data integrity\n- **Audit Preparation**: Validate data quality before audits\n- **Maintenance Planning**: Identify and prioritize data cleanup tasks\n- **Performance Optimization**: Find and resolve performance-impacting issues\n- **Compliance Monitoring**: Ensure data meets regulatory requirements\n\n## Fiscal Year Support\n- **Fiscal Year Filtering**: Optional fiscal year start date parameter\n- **Period Analysis**: Health check for specific accounting periods\n- **Year-End Validation**: Comprehensive validation before year-end closing\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Fiscal year start date in YYYYMMDD format for period-specific analysis",
            "example": 20240401,
            "in": "query",
            "name": "fiscal_year_start",
            "required": false,
            "schema": {
              "maximum": 99991231,
              "minimum": 19000101,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DataIntegrityResponse"
                }
              }
            },
            "description": "Data integrity health check completed successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get data integrity health check",
        "tags": [
          "Journal Entries"
        ]
      }
    },
    "/journal-entries/import": {
      "post": {
        "description": "Bulk import journal entries from pre-parsed CSV data.\n\n## CSV Import Feature (v4.30+)\nImport journal entries from Japanese accounting software:\n- **MoneyForward**: Auto-detected format\n- **freee**: Auto-detected format\n- **Yayoi (弥生会計)**: Full support\n- **PCA**: Full support\n- **JDL IBEX**: Full support\n- **MJS (ミロク)**: Full support\n\n## Import Process\n1. **Frontend parses CSV**: Frontend uses parseJapaneseAccountingCsv utility\n2. **Format detection**: Auto-detect source software format\n3. **Data validation**: Validate entry structure and amounts\n4. **Account resolution**: Backend resolves account codes to IDs\n5. **Persistence**: Entries saved with source_type 'csv_import'\n\n## Validation Rules\n- Each entry must have at least 2 lines (debit and credit)\n- Debit total must equal credit total\n- All account codes must exist in the system\n- Entry dates must be valid YYYYMMDD format\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "freee_import": {
                  "summary": "Import from freee",
                  "value": {
                    "entries": [
                      {
                        "description": "経費精算",
                        "entry_date": 20260120,
                        "lines": [
                          {
                            "account_code": "7101",
                            "credit_amount": 0,
                            "debit_amount": 5500,
                            "description": "交通費"
                          },
                          {
                            "account_code": "1110",
                            "credit_amount": 5500,
                            "debit_amount": 0
                          }
                        ]
                      }
                    ],
                    "filename": "freee_仕訳データ.csv",
                    "source": "freee"
                  }
                },
                "yayoi_import": {
                  "summary": "Import from Yayoi (弥生会計)",
                  "value": {
                    "entries": [
                      {
                        "description": "売上計上",
                        "entry_date": 20260115,
                        "lines": [
                          {
                            "account_code": "1110",
                            "credit_amount": 0,
                            "debit_amount": 110000
                          },
                          {
                            "account_code": "4100",
                            "credit_amount": 100000,
                            "debit_amount": 0
                          },
                          {
                            "account_code": "2150",
                            "credit_amount": 10000,
                            "debit_amount": 0,
                            "description": "消費税"
                          }
                        ]
                      }
                    ],
                    "filename": "yayoi_export_2026.csv",
                    "source": "yayoi"
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/ImportJournalEntriesRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ImportJournalEntriesResponse"
                }
              }
            },
            "description": "All entries imported successfully"
          },
          "207": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ImportJournalEntriesResponse"
                }
              }
            },
            "description": "Partial success - some entries had errors"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "At least one journal entry is required",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid request or validation errors"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Import journal entries from CSV",
        "tags": [
          "Journal Entries"
        ]
      }
    },
    "/journal-entries/opening-balance": {
      "post": {
        "description": "Create opening balance journal entry for fiscal year initialization with Japanese accounting standards.\n\n## Opening Balance Creation (期首残高設定)\nCreates comprehensive opening balance entry with:\n- **Fiscal Year Setup**: Initialize account balances for new fiscal year\n- **Account Balances**: Set opening balances for all relevant accounts\n- **Double-Entry Validation**: Ensure total debits equal total credits\n- **Audit Trail**: Complete documentation of opening balance creation\n- **Japanese Standards**: Aligned with Japanese fiscal year and accounting practices\n\n## Opening Balance Components\n- **Asset Accounts**: Cash, receivables, inventory, fixed assets\n- **Liability Accounts**: Payables, accrued expenses, loans\n- **Equity Accounts**: Capital, retained earnings, reserves\n- **Balance Validation**: Automatic validation of accounting equation (Assets = Liabilities + Equity)\n\n## Fiscal Year Integration\n- **Fiscal Year Start**: Typically April 1st for Japanese businesses\n- **Account Initialization**: Set up all account balances for new period\n- **Prior Year Closing**: Integration with previous year closing balances\n- **Audit Preparation**: Opening balances ready for audit review\n\n## Japanese Accounting Standards\n- **Chart of Accounts**: Integration with Japanese standard account codes\n- **Financial Reporting**: Opening balances for Japanese financial statements\n- **Tax Compliance**: Proper opening balance documentation for tax filing\n- **Audit Requirements**: Opening balance support for statutory audits\n\n## Validation Rules\n- **Balance Equation**: Total debits must equal total credits\n- **Account Validation**: All accounts must exist and be active\n- **Date Validation**: Entry date must be valid fiscal year start\n- **Amount Validation**: All amounts must be non-negative\n- **Duplicate Prevention**: Prevents duplicate opening balance entries\n\n## Use Cases\n- **Fiscal Year Setup**: Initialize new fiscal year accounting\n- **System Migration**: Set opening balances when migrating to new system\n- **Audit Preparation**: Establish proper opening balances for audit\n- **Financial Reporting**: Ensure accurate starting balances for reports\n- **Compliance**: Meet Japanese accounting standards for opening balances\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "fiscal_year_opening": {
                  "summary": "Fiscal year opening balance",
                  "value": {
                    "description": "令和6年度 期首残高",
                    "entry_date": 20240401,
                    "lines": [
                      {
                        "account_id": "456e7890-f12a-34b5-c678-901234567890",
                        "credit_amount": 0,
                        "debit_amount": 1000000,
                        "description": "現金 期首残高"
                      },
                      {
                        "account_id": "789e0123-e45b-67c8-d901-234567890123",
                        "credit_amount": 0,
                        "debit_amount": 500000,
                        "description": "売掛金 期首残高"
                      },
                      {
                        "account_id": "abc12345-def6-7890-ghij-klmnopqrstuv",
                        "credit_amount": 1500000,
                        "debit_amount": 0,
                        "description": "資本金 期首残高"
                      }
                    ]
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/CreateOpeningBalanceRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/OpeningBalanceResponse"
                }
              }
            },
            "description": "Opening balance created successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "details": {
                      "properties": {
                        "difference": {
                          "example": 100000,
                          "type": "number"
                        },
                        "totalCredits": {
                          "example": 1400000,
                          "type": "number"
                        },
                        "totalDebits": {
                          "example": 1500000,
                          "type": "number"
                        }
                      },
                      "type": "object"
                    },
                    "error": {
                      "example": "Opening balance entry is not balanced (debits ≠ credits)",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid opening balance data or unbalanced entry"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "409": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Opening balance already exists for fiscal year 2024",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Opening balance already exists for this date"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create opening balance entry",
        "tags": [
          "Journal Entries"
        ]
      }
    },
    "/journal-entries/orphans": {
      "delete": {
        "description": "Delete all orphan journal entries (entries with no lines).\n\n## ⚠️ Destructive Operation\nThis permanently removes orphan entries. Use with caution.\n\n## Recommended Workflow\n1. First call `GET /api/journal-entries/orphans` to review entries\n2. If entries should be regenerated, use `POST /api/journal-entries/orphans/regenerate`\n3. Only use this DELETE if entries cannot be regenerated\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "cleaned": {
                          "example": 5,
                          "type": "integer"
                        },
                        "deletedEntries": {
                          "items": {
                            "type": "object"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Cleaned 5 orphan journal entries",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Orphan entries deleted successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Delete all orphan journal entries",
        "tags": [
          "Journal Entries"
        ]
      },
      "get": {
        "description": "Find journal entries that have no line items (orphan entries).\n\n## Orphan Entry Detection\nIdentifies journal entries without corresponding line items:\n- **Entry Header Only**: Journal entry record exists but has no debit/credit lines\n- **Data Integrity**: Indicates incomplete journal entry creation\n- **Cleanup Candidates**: Entries that may need regeneration or deletion\n\n## Use Cases\n- **Data Quality**: Identify incomplete entries for data quality improvement\n- **Maintenance**: Find entries needing attention before month-end\n- **Troubleshooting**: Diagnose journal entry generation issues\n- **Audit Preparation**: Clean up data before audit\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "items": {
                        "properties": {
                          "description": {
                            "type": "string"
                          },
                          "entry_date": {
                            "example": 20251128,
                            "type": "integer"
                          },
                          "entry_number": {
                            "example": "JE-20251128-mlgml",
                            "type": "string"
                          },
                          "id": {
                            "format": "uuid",
                            "type": "string"
                          },
                          "reference_document_id": {
                            "format": "uuid",
                            "nullable": true,
                            "type": "string"
                          }
                        },
                        "type": "object"
                      },
                      "type": "array"
                    },
                    "message": {
                      "example": "5件の不完全な仕訳が見つかりました",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Orphan entries found successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Find orphan journal entries",
        "tags": [
          "Journal Entries"
        ]
      }
    },
    "/journal-entries/orphans/regenerate": {
      "post": {
        "description": "Automatically find and regenerate all orphan journal entries from their source documents.\n\n## 🔧 One-Click Orphan Fix - v4.54 Parallel\n\nThis endpoint with **~3x faster** parallel execution:\n1. **Finds** all orphan entries (entries with no lines)\n2. **Parallel Processing (v4.54)**: Regenerates up to 3 entries concurrently\n3. **Deletes** related general_ledger_lines (handles FK constraints)\n4. **Deletes** the incomplete entry headers\n5. **Regenerates** journal entries from source documents using `forceRegenerate` mode\n6. **Reports** success/failure for each entry\n\n## Performance (v4.54)\n\n| Orphans | Before (Sequential) | After (Parallel) | Speedup |\n|---------|---------------------|------------------|---------|\n| 5       | ~10s                | ~3.5s            | ~3x     |\n| 10      | ~20s                | ~7s              | ~3x     |\n| 20      | ~40s                | ~14s             | ~3x     |\n\n## Technical Implementation (v4.54)\n- **Sliding Window Concurrency**: 3 parallel regenerations\n- **Per-Item Processing**: Each entry processed independently\n- **Error Isolation**: Failed entries don't block others\n- **FK Constraint Handling**: Orphan entries may have `general_ledger_lines` even without `journal_entry_lines`. These are deleted first.\n- **Force Regenerate Mode**: Uses `forceRegenerate=true` to ensure existing orphans are properly cleaned up before regeneration.\n\n## Why Orphan Entries Exist\nOrphan entries can occur due to:\n- **Timeout**: Long-running transactions that timed out\n- **Missing Data**: Source document missing required data at generation time\n- **Account Mapping**: Missing expense category to account mappings\n- **Historical**: Entries created before event-driven automation was implemented\n\n## Response Details\nReturns detailed results for each regenerated entry:\n- **documentId**: Source document identifier\n- **documentName**: Human-readable document name\n- **success**: Whether regeneration succeeded\n- **error**: Error message if regeneration failed\n\n## Best Practice\nUse this endpoint for one-time cleanup of existing orphan entries.\nGoing forward, journal entries are automatically generated when documents are published.\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "failed": {
                          "example": 1,
                          "type": "integer"
                        },
                        "regenerated": {
                          "example": 5,
                          "type": "integer"
                        },
                        "results": {
                          "items": {
                            "properties": {
                              "documentId": {
                                "format": "uuid",
                                "type": "string"
                              },
                              "documentName": {
                                "example": "20250703-04_kita_karuizawa_trip",
                                "type": "string"
                              },
                              "error": {
                                "nullable": true,
                                "type": "string"
                              },
                              "success": {
                                "example": true,
                                "type": "boolean"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Regenerated 5 entries, 1 failed",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Bulk regeneration completed"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Bulk regenerate all orphan journal entries (v4.54 Parallel)",
        "tags": [
          "Journal Entries"
        ]
      }
    },
    "/journal-entries/regenerate/{document_id}": {
      "post": {
        "description": "Regenerate a journal entry for a specific document by first deleting any orphan entry and then recreating.\n\n## Single Document Regeneration\n- **Orphan Check**: Finds existing orphan entry for the document\n- **Cleanup**: Deletes the incomplete entry header\n- **Regeneration**: Creates new journal entry from document data\n\n## Error Handling\n- Returns 409 if a valid journal entry (with lines) already exists\n- Returns 409 (`data.reason = CLAIM_LINES_NOT_POSTABLE`) for a 立替経費申請 whose rows cannot be posted: a row with no yen, a JPY row whose yen differs from its amount, an unconverted foreign row, a row another posted entry already books, or a claim already paid by a transfer whose entry booked the expenses directly. With `force` this is checked BEFORE the existing entry is reversed, so a refused claim keeps it.\n- Returns 404 if document not found\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Document ID to regenerate journal entry for",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/JournalEntryResponse"
                }
              }
            },
            "description": "Journal entry regenerated successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetails"
                }
              }
            },
            "description": "Valid journal entry already exists, or the 立替経費申請 rows cannot be posted (data.reason = CLAIM_LINES_NOT_POSTABLE; detail names each row and how to fix it)"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Regenerate journal entry for a single document",
        "tags": [
          "Journal Entries"
        ]
      }
    },
    "/journal-entries/summary": {
      "get": {
        "description": "Retrieve comprehensive summary statistics for journal entries with financial totals and breakdowns.\n\n## Financial Summary Overview\nReturns detailed journal entry statistics:\n- **Entry Counts**: Total entries and breakdown by status\n- **Financial Totals**: Total debit and credit amounts\n- **Source Analysis**: Entry distribution by source type\n- **Period Analysis**: Summary for specified date range\n- **Balance Validation**: Verification of double-entry bookkeeping principles\n\n## Summary Metrics\n- **Total Entries**: Complete count of journal entries in system\n- **Debit/Credit Totals**: Sum of all debit and credit amounts\n- **Status Distribution**: Count of draft, posted, and reversed entries\n- **Source Distribution**: Breakdown by entry source (manual, document-generated, etc.)\n- **Balance Verification**: Confirmation that total debits equal total credits\n\n## Period Filtering\n- **Date Range**: Optional start and end date filtering\n- **Fiscal Period**: Summary for specific fiscal periods\n- **Monthly Analysis**: Month-by-month summary data\n- **Year-to-Date**: Cumulative summary from fiscal year start\n\n## Use Cases\n- **Dashboard Widgets**: Key financial metrics for accounting dashboards\n- **Financial Analysis**: High-level analysis of journal entry activity\n- **Audit Overview**: Summary data for audit preparation and review\n- **Performance Monitoring**: Track journal entry volume and processing\n- **Compliance Reporting**: Summary data for regulatory reporting\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Start date for summary period in YYYYMMDD format",
            "example": 20240401,
            "in": "query",
            "name": "start_date",
            "required": false,
            "schema": {
              "maximum": 99991231,
              "minimum": 19000101,
              "type": "integer"
            }
          },
          {
            "description": "End date for summary period in YYYYMMDD format",
            "example": 20241231,
            "in": "query",
            "name": "end_date",
            "required": false,
            "schema": {
              "maximum": 99991231,
              "minimum": 19000101,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/JournalSummaryResponse"
                }
              }
            },
            "description": "Journal entries summary retrieved successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Invalid date format (use YYYYMMDD)",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid date parameters"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get journal entries summary",
        "tags": [
          "Journal Entries"
        ]
      }
    },
    "/journal-entries/{id}/lineage-diff": {
      "get": {
        "description": "Read-only comparison between the amount extracted from the source document and the amount actually posted for one journal entry.\n\nExtraction source, in priority order:\n1. `expense_wizard_items.extracted_amount_jpy` (typed)\n2. `file_uploads.ai_data` / `verdict` JSON (probed defensively per parse engine)\n\nReturns `hasSource:false, hops:[]` when no extracted source is found (never an error). 404 only when the entry does not exist or is not owned.",
        "parameters": [
          {
            "description": "Journal entry UUID",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/JournalLineageDiffResponse"
                }
              }
            },
            "description": "Journal lineage diff retrieved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Per-hop 転記ミス diff (書類金額 vs 仕訳金額)",
        "tags": [
          "Journal Entries"
        ]
      }
    },
    "/journal-entries/{journal_entry_id}/reverse": {
      "post": {
        "description": "Reverse one posted journal entry that is NOT tied to a bank transaction — adjustments, reclassifications, manual entries.\n\nLines are soft-deleted with the reason, the header becomes `reversed` (reversal_reason / reversed_at / reversed_by stamped), the general-ledger lines are retired by trigger and the change is captured in 訂正削除履歴.\n\n- 409 when the entry is already reversed, or when a bank row / reconciliation link points at it — bank-linked entries are corrected from the bank panel's 修正モード so the row is re-pointed at the replacement.\n- 423 when the entry date falls in a filed fiscal period (filed-period lock).\n- The period lock (closed periods) applies on the entry date.",
        "parameters": [
          {
            "description": "Journal entry UUID",
            "in": "path",
            "name": "journal_entry_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "reason": {
                    "description": "取消理由 — stored on the entry and every line (deletion_reason) and in the bypass audit row",
                    "example": "科目是正の重複（同じ訂正が二重に振替されていた）",
                    "maxLength": 200,
                    "minLength": 1,
                    "type": "string"
                  }
                },
                "required": [
                  "reason"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/JournalReverseResponse"
                }
              }
            },
            "description": "Journal entry reversed"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetails"
                }
              }
            },
            "description": "Already reversed, or the entry is tied to a bank row (use the bank panel 修正モード)"
          },
          "423": {
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetails"
                }
              }
            },
            "description": "The entry date is in a filed fiscal year (PERIOD_LOCKED) and no 修正申告 for that year is open"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "取消 a posted entry that has no bank row (BL-393)",
        "tags": [
          "Journal Entries"
        ]
      }
    },
    "/journal-entries/{journal_entry_id}/tag-advisor-instruction": {
      "patch": {
        "description": "Marks one journal entry as booked on the 税理士's instruction: sets `reference_type = 'advisor_instruction'` and prefixes the description with 「税理士指示による修正：<note>｜」 (or 「税理士指示による修正｜」 without a note).\n\nIdempotent on the description: an entry whose description already starts with 税理士指示 is not prefixed again. The body is required but may be `{}`.",
        "parameters": [
          {
            "description": "Journal entry UUID",
            "in": "path",
            "name": "journal_entry_id",
            "required": true,
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "Optional (X-Idempotency-Key also accepted); a repeated key is deduplicated",
            "in": "header",
            "name": "Idempotency-Key",
            "required": false,
            "schema": {
              "maxLength": 64,
              "minLength": 16,
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "note": {
                    "description": "税理士指示の内容",
                    "example": "交際費から会議費へ振替",
                    "maxLength": 200,
                    "minLength": 1,
                    "type": "string"
                  }
                },
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "description": {
                          "example": "税理士指示による修正：交際費から会議費へ振替｜打合せ飲食代",
                          "type": "string"
                        },
                        "id": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "lastEditedAt": {
                          "format": "date-time",
                          "nullable": true,
                          "type": "string"
                        },
                        "referenceType": {
                          "example": "advisor_instruction",
                          "nullable": true,
                          "type": "string"
                        }
                      },
                      "required": [
                        "id",
                        "description",
                        "referenceType",
                        "lastEditedAt"
                      ],
                      "type": "object"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Entry tagged"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "税理士指示タグ付け (trust-layer Phase F)",
        "tags": [
          "Journal Entries"
        ]
      }
    },
    "/journal-templates": {
      "get": {
        "description": "Get all journal templates for the authenticated user with intelligent sorting.\n\n## Journal Templates (仕訳辞書)\nComprehensive template management with:\n- **Template Library**: Complete collection of user's journal templates\n- **Intelligent Sorting**: Sorted by shortcut key priority, usage frequency, and name\n- **Usage Tracking**: Templates sorted by usage count for quick access to frequently used templates\n- **Shortcut Integration**: F1-F5 shortcut keys for rapid template access\n- **Active/Inactive Filtering**: Option to include or exclude inactive templates\n\n## Sorting Logic\nTemplates are sorted in the following priority order:\n1. **Shortcut Key Priority**: Templates with shortcut keys (F1-F5) appear first\n2. **Usage Frequency**: Within each group, sorted by usage count (most used first)\n3. **Alphabetical Order**: Finally sorted alphabetically by name for consistency\n\n## Template Information\nEach template includes:\n- **Basic Information**: Name, description, shortcut key assignment\n- **Account Details**: Complete debit and credit account information with codes and names\n- **Default Values**: Default amount and description for quick entry creation\n- **Tax Settings**: Tax rate classification and tax inclusion preferences\n- **Usage Statistics**: Usage count for popularity tracking\n- **Status Information**: Active/inactive status and timestamps\n\n## Use Cases\n- **Template Selection**: Browse and select templates for journal entry creation\n- **Usage Analysis**: Analyze template usage patterns for workflow optimization\n- **Template Management**: Review template library for maintenance and updates\n- **Shortcut Planning**: Plan shortcut key assignments based on usage frequency\n- **Workflow Optimization**: Identify most frequently used templates for quick access\n\n## Filtering Options\n- **Active Only (default)**: Show only active templates for normal operations\n- **Include Inactive**: Include inactive templates for comprehensive management\n\nBearer token authentication required.",
        "parameters": [
          {
            "description": "Include inactive templates (default: false)",
            "example": false,
            "in": "query",
            "name": "include_inactive",
            "required": false,
            "schema": {
              "default": false,
              "type": "boolean"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/JournalTemplateListResponse"
                }
              }
            },
            "description": "Journal templates retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List journal templates (仕訳辞書一覧)",
        "tags": [
          "Journal Templates"
        ]
      },
      "post": {
        "description": "Create a new journal template for automated accounting entry creation.\n\n## Template Creation\nComprehensive template setup with:\n- **Account Configuration**: Debit and credit account assignments with validation\n- **Default Values**: Optional default amount and description for quick entry\n- **Shortcut Assignment**: Optional F1-F5 shortcut key for rapid access\n- **Tax Configuration**: Japanese consumption tax rate and inclusion settings\n- **Template Metadata**: Name, description, and usage tracking initialization\n\n## Account Validation\n- **Account Existence**: Validates that both debit and credit accounts exist\n- **Account Access**: Ensures accounts are accessible to the user\n- **Chart Integration**: Integrates with chart of accounts for proper classification\n- **Relationship Integrity**: Maintains proper account relationship references\n\n## Shortcut Key Management\n- **Uniqueness Validation**: Ensures shortcut keys are unique per user\n- **F1-F5 Range**: Supports F1 through F5 shortcut key assignments\n- **Optional Assignment**: Shortcut keys are optional for flexible template management\n- **Conflict Resolution**: Prevents shortcut key conflicts with clear error messages\n\n## Tax Rate Support\nSupports Japanese consumption tax classifications:\n- **standard_10**: Standard 10% consumption tax rate\n- **reduced_8**: Reduced 8% rate for eligible items\n- **non_taxable**: Non-taxable transactions\n- **tax_exempt**: Tax-exempt transactions\n- **outside_scope**: Transactions outside tax scope\n\n## Template Features\n- **Default Values**: Set default amounts and descriptions for consistent entry creation\n- **Tax Inclusion**: Configure whether amounts include or exclude tax\n- **Usage Tracking**: Automatic usage count initialization for analytics\n- **Active Status**: Templates created as active by default\n\nBearer token authentication required.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateJournalTemplateRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/JournalTemplateCreateResponse"
                }
              }
            },
            "description": "Journal template created successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "ACCOUNT_NOT_FOUND",
                      "type": "string"
                    },
                    "error": {
                      "example": "Debit account not found",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Account not found"
          },
          "409": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "SHORTCUT_CONFLICT",
                      "type": "string"
                    },
                    "error": {
                      "example": "Shortcut key F1 is already in use",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Shortcut key already in use"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create journal template (仕訳辞書作成)",
        "tags": [
          "Journal Templates"
        ]
      }
    },
    "/journal-templates/{id}": {
      "delete": {
        "description": "Delete a journal template using soft delete to preserve audit trail.\n\n## Soft Delete Implementation\nSafe template removal with:\n- **Audit Trail Preservation**: Template data preserved for audit purposes\n- **Status Deactivation**: Template marked as inactive rather than physically deleted\n- **Shortcut Release**: Shortcut key freed for reassignment to other templates\n- **Usage History**: Usage statistics and history preserved\n- **Reversible Operation**: Template can be reactivated if needed\n\n## Delete Process\n1. **Ownership Validation**: Verify template belongs to authenticated user\n2. **Status Update**: Mark template as inactive (is_active = false)\n3. **Shortcut Release**: Clear shortcut key assignment to free for reuse\n4. **Timestamp Update**: Update modification timestamp\n5. **Audit Logging**: Log deletion operation for audit trail\n\n## Impact on Operations\n- **Template Lists**: Deleted templates excluded from default lists\n- **Shortcut Keys**: Freed shortcut keys available for new assignments\n- **Usage Statistics**: Historical usage data preserved\n- **Journal Entries**: Existing journal entries created from template unaffected\n\n## Use Cases\n- **Template Cleanup**: Remove unused or obsolete templates\n- **Workflow Optimization**: Clean up template library for better organization\n- **Shortcut Management**: Free shortcut keys for more frequently used templates\n- **Template Maintenance**: Remove templates that are no longer relevant\n\n## Recovery Options\n- **Reactivation**: Templates can be reactivated by updating is_active status\n- **Data Preservation**: All template data preserved for potential recovery\n- **Audit Trail**: Complete history of template lifecycle maintained\n\nBearer token authentication required.",
        "parameters": [
          {
            "description": "Template ID",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/JournalTemplateDeleteResponse"
                }
              }
            },
            "description": "Journal template deleted successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Delete journal template (soft delete)",
        "tags": [
          "Journal Templates"
        ]
      },
      "get": {
        "description": "Get detailed information about a specific journal template.\n\n## Template Details\nComprehensive template information with:\n- **Complete Template Data**: All template fields including metadata\n- **Account Information**: Detailed debit and credit account information\n- **Usage Statistics**: Current usage count and activity status\n- **Configuration Details**: Tax settings, default values, and shortcut assignments\n- **Relationship Data**: Complete account relationship information with codes and names\n\n## Account Integration\n- **Account Details**: Full account information including code, name, and type\n- **Chart Integration**: Integration with chart of accounts for proper classification\n- **Relationship Integrity**: Maintains proper account relationship references\n- **Access Validation**: Ensures template belongs to authenticated user\n\n## Use Cases\n- **Template Review**: Review template configuration before use\n- **Template Editing**: Retrieve current values for template updates\n- **Usage Analysis**: Analyze template usage statistics\n- **Account Verification**: Verify account assignments and relationships\n- **Template Application**: Retrieve template data for journal entry creation\n\n## Security\n- **User Isolation**: Templates are isolated by user ID\n- **Access Control**: Only template owner can access template details\n- **Authentication Required**: Bearer token authentication required\n\nBearer token authentication required.",
        "parameters": [
          {
            "description": "Template ID",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/JournalTemplateResponse"
                }
              }
            },
            "description": "Journal template retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get journal template by ID",
        "tags": [
          "Journal Templates"
        ]
      },
      "put": {
        "description": "Update an existing journal template with new configuration.\n\n## Template Updates\nComprehensive template modification with:\n- **Flexible Updates**: Update any template field independently\n- **Account Changes**: Modify debit and credit account assignments with validation\n- **Shortcut Management**: Change or remove shortcut key assignments\n- **Configuration Updates**: Modify tax settings, default values, and descriptions\n- **Status Management**: Activate or deactivate templates\n\n## Validation Rules\n- **Account Validation**: Validates new account assignments if changed\n- **Shortcut Uniqueness**: Ensures shortcut key uniqueness when modified\n- **User Ownership**: Validates template belongs to authenticated user\n- **Relationship Integrity**: Maintains proper account relationship references\n\n## Update Features\n- **Partial Updates**: Only specified fields are updated\n- **Timestamp Management**: Automatic updated_at timestamp management\n- **Account Integration**: Real-time account validation and relationship updates\n- **Shortcut Conflict Resolution**: Prevents shortcut key conflicts\n\n## Use Cases\n- **Template Maintenance**: Update template configuration as business needs change\n- **Account Changes**: Update account assignments when chart of accounts changes\n- **Shortcut Reassignment**: Reassign shortcut keys for optimal workflow\n- **Status Management**: Activate or deactivate templates based on usage\n- **Configuration Tuning**: Fine-tune default values and tax settings\n\n## Security\n- **User Isolation**: Only template owner can update templates\n- **Access Control**: Authentication and ownership validation required\n- **Data Integrity**: Comprehensive validation prevents data corruption\n\nBearer token authentication required.",
        "parameters": [
          {
            "description": "Template ID",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateJournalTemplateRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/JournalTemplateUpdateResponse"
                }
              }
            },
            "description": "Journal template updated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "SHORTCUT_CONFLICT",
                      "type": "string"
                    },
                    "error": {
                      "example": "Shortcut key F1 is already in use",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Shortcut key already in use"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update journal template",
        "tags": [
          "Journal Templates"
        ]
      }
    },
    "/journal-templates/{id}/apply": {
      "post": {
        "description": "Apply a journal template to create a new journal entry with user-provided data.\n\n## Template Application\nAutomated journal entry creation with:\n- **Template Integration**: Uses template's account assignments and default values\n- **User Input Override**: User-provided amount and description override template defaults\n- **Tax Calculation**: Automatic tax calculation based on template tax settings\n- **Usage Tracking**: Increments template usage count for analytics\n- **Entry Generation**: Creates complete journal entry with debit and credit lines\n\n## Application Process\n1. **Template Retrieval**: Fetch template with account information\n2. **Data Validation**: Validate user input (date, amount, description)\n3. **Value Resolution**: Use user input or template defaults as appropriate\n4. **Tax Calculation**: Calculate tax amounts based on template settings\n5. **Entry Creation**: Create journal entry with debit and credit lines\n6. **Usage Update**: Increment template usage count\n7. **Response Generation**: Return created journal entry details\n\n## Data Override Logic\n- **Amount**: User-provided amount always overrides template default\n- **Description**: User description overrides template default, fallback to template\n- **Date**: User-provided entry date (required)\n- **Accounts**: Template account assignments used (not overridable)\n- **Tax Settings**: Template tax rate and inclusion settings used\n\n## Tax Handling\n- **Tax Rate**: Uses template's configured tax rate\n- **Tax Inclusion**: Respects template's tax inclusion setting\n- **Tax Calculation**: Automatic calculation for tax-inclusive/exclusive amounts\n- **Japanese Standards**: Complies with Japanese consumption tax regulations\n\n## Usage Analytics\n- **Usage Tracking**: Increments template usage count for popularity analytics\n- **Sorting Impact**: Increased usage count improves template sorting position\n- **Workflow Optimization**: Usage data helps optimize template organization\n\n## Use Cases\n- **Quick Entry Creation**: Rapidly create journal entries using predefined templates\n- **Consistent Accounting**: Ensure consistent account assignments across similar transactions\n- **Workflow Automation**: Automate repetitive journal entry creation\n- **Error Reduction**: Reduce manual entry errors through template automation\n- **Efficiency Improvement**: Improve accounting workflow efficiency\n\nBearer token authentication required.",
        "parameters": [
          {
            "description": "Template ID",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ApplyTemplateRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/JournalEntryCreateResponse"
                }
              }
            },
            "description": "Journal entry created from template successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Apply template to create journal entry (仕訳辞書適用)",
        "tags": [
          "Journal Templates"
        ]
      }
    },
    "/ledger/freee/connect": {
      "get": {
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "auth_url": {
                          "format": "uri",
                          "type": "string"
                        },
                        "available": {
                          "type": "boolean"
                        },
                        "state": {
                          "type": "string"
                        }
                      },
                      "type": "object"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "OAuth redirect URL"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Initiate freee OAuth authorization",
        "tags": [
          "Ledger Integration"
        ]
      }
    },
    "/ledger/freee/disconnect": {
      "post": {
        "responses": {
          "200": {
            "description": "Disconnected"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Disconnect freee integration",
        "tags": [
          "Ledger Integration"
        ]
      }
    },
    "/ledger/status": {
      "get": {
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "connections": {
                          "items": {
                            "$ref": "#/components/schemas/LedgerConnection"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Connection status"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get ledger connection status",
        "tags": [
          "Ledger Integration"
        ]
      }
    },
    "/ledger/sync": {
      "post": {
        "responses": {
          "202": {
            "description": "Sync queued"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Trigger manual ledger sync",
        "tags": [
          "Ledger Integration"
        ]
      }
    },
    "/map/batch-tiles": {
      "post": {
        "description": "Fetch multiple map tiles in a single batch request for dramatically improved performance.\n\n## Batch Tile Fetching\nHigh-performance tile loading with:\n- **Reduced Latency**: Fetch up to 25 tiles in one request instead of 25 separate requests\n- **Parallel Processing**: Server-side parallel fetching of tiles from MLIT GIS APIs\n- **Intelligent Caching**: Automatic cache management with LRU and TTL strategies\n- **Compression**: Automatic gzip compression for large responses (60-80% reduction)\n- **Performance Optimization**: Geometry simplification and point clustering options\n\n## Optimization Features\n- **Geometry Simplification**: Reduce geometry complexity for better performance at lower zoom levels\n- **Point Clustering**: Group nearby points to reduce feature count and improve rendering\n- **Cache Integration**: Automatic cache lookup and population for subsequent requests\n- **Error Handling**: Graceful handling of individual tile failures without affecting the entire batch\n\n## MLIT GIS API Integration\n- **Layer Support**: Support for all major MLIT GIS layers (use zones, transactions, etc.)\n- **Static vs Dynamic**: Optimized caching strategies for static (24h TTL) vs dynamic (15min TTL) layers\n- **Parameter Support**: Full support for MLIT API parameters and options\n- **Format Support**: GeoJSON and other response formats\n\n## Performance Benefits\n- **Latency Reduction**: 80-90% reduction in total request time for viewport loading\n- **Network Efficiency**: Fewer HTTP connections and reduced overhead\n- **Cache Efficiency**: Intelligent cache warming and hit rate optimization\n- **Memory Management**: Efficient memory usage with automatic cleanup\n\n## Use Cases\n- **Viewport Loading**: Load all tiles for a map viewport in one request\n- **Prefetching**: Batch prefetch tiles for smooth panning experience\n- **Offline Preparation**: Download tiles for offline map applications\n- **Performance Optimization**: Optimize map loading performance for real estate applications\n\nAuthentication not required for public map data access.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/BatchTileRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BatchTileResponse"
                }
              }
            },
            "description": "Batch tiles fetched successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "INVALID_REQUEST",
                      "type": "string"
                    },
                    "message": {
                      "example": "apiCode and tiles array required",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid request parameters"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "Fetch multiple GIS tiles in a single request",
        "tags": [
          "Map Streaming"
        ]
      }
    },
    "/map/cache": {
      "delete": {
        "description": "Clear the tile cache completely or for a specific layer.\n\n## Cache Management\nAdministrative cache control with:\n- **Complete Clear**: Clear entire cache for fresh start\n- **Layer-Specific Clear**: Clear cache for specific GIS layers\n- **Memory Recovery**: Free up memory used by cached tiles\n- **Performance Reset**: Reset cache statistics and performance counters\n- **Administrative Control**: Administrative function for cache management\n\n## Clear Options\n- **Full Cache Clear**: Remove all cached tiles and reset statistics\n- **Layer-Specific Clear**: Remove tiles for specific MLIT GIS layers\n- **Selective Clearing**: Target specific cache segments for optimization\n- **Statistics Reset**: Reset performance counters and statistics\n\n## Use Cases\n- **Memory Management**: Free up memory when cache grows too large\n- **Data Refresh**: Clear cache when underlying data has been updated\n- **Performance Issues**: Clear cache to resolve performance problems\n- **Testing**: Clear cache for testing and development purposes\n- **Maintenance**: Regular cache maintenance and cleanup\n\n## Administrative Functions\n- **System Maintenance**: Part of regular system maintenance procedures\n- **Performance Optimization**: Clear cache to optimize performance\n- **Memory Management**: Manage server memory usage\n- **Data Consistency**: Ensure data consistency after updates\n\n## Impact Considerations\n- **Performance Impact**: Clearing cache will temporarily reduce performance\n- **Memory Recovery**: Immediate memory recovery after cache clear\n- **Statistics Reset**: Cache statistics will be reset to zero\n- **Gradual Recovery**: Cache performance will gradually improve as cache repopulates\n\nAuthentication not required but should be restricted to administrators in production.",
        "parameters": [
          {
            "description": "Optional: clear specific layer only",
            "example": "XKT002",
            "in": "query",
            "name": "layer",
            "required": false,
            "schema": {
              "$ref": "#/components/schemas/MLITGISAPICode"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "message": {
                      "example": "Entire tile cache cleared",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Cache cleared successfully"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "Clear tile cache",
        "tags": [
          "Map Streaming"
        ]
      }
    },
    "/map/cache/stats": {
      "get": {
        "description": "Get detailed statistics about the tile cache performance and usage.\n\n## Cache Statistics\nComprehensive cache monitoring with:\n- **Hit Rate Analysis**: Cache hit rate and miss statistics for performance monitoring\n- **Memory Usage**: Current memory usage and capacity information\n- **Entry Management**: Total entries, oldest/newest entry ages for cache health\n- **Performance Metrics**: Detailed metrics for cache optimization\n- **Formatted Output**: Human-readable formatted statistics for easy interpretation\n\n## Performance Monitoring\n- **Hit Rate Tracking**: Monitor cache effectiveness over time\n- **Memory Management**: Track memory usage and optimize cache size\n- **Age Analysis**: Monitor entry ages to optimize TTL settings\n- **Efficiency Metrics**: Measure cache efficiency and identify optimization opportunities\n\n## Cache Health\n- **Capacity Monitoring**: Monitor cache capacity and prevent overflow\n- **Entry Distribution**: Analyze entry distribution and access patterns\n- **Performance Trends**: Track performance trends over time\n- **Optimization Opportunities**: Identify areas for cache optimization\n\n## Use Cases\n- **Performance Monitoring**: Monitor cache performance in production\n- **Capacity Planning**: Plan cache capacity based on usage patterns\n- **Optimization**: Identify and implement cache optimizations\n- **Debugging**: Debug cache-related performance issues\n- **Reporting**: Generate performance reports for stakeholders\n\n## Metrics Included\n- **Hit/Miss Rates**: Detailed hit and miss statistics\n- **Memory Usage**: Current memory usage in MB\n- **Entry Ages**: Oldest and newest entry ages\n- **Cache Size**: Total number of cached entries\n- **Performance Ratios**: Calculated performance ratios and percentages\n\nAuthentication not required for cache statistics.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CacheStatsResponse"
                }
              }
            },
            "description": "Cache statistics retrieved successfully"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "Get comprehensive cache statistics",
        "tags": [
          "Map Streaming"
        ]
      }
    },
    "/map/compression-info": {
      "get": {
        "description": "Get information about compression options and recommendations for optimal performance.\n\n## Compression Information\nComprehensive compression guidance with:\n- **Supported Formats**: List of supported compression formats (gzip, brotli)\n- **Performance Benefits**: Detailed information about compression benefits\n- **Implementation Guidance**: How to implement compression in client applications\n- **Format Recommendations**: Specific recommendations for different data types\n- **Header Information**: Required HTTP headers for compression support\n\n## Compression Benefits\n- **GeoJSON Compression**: 60-80% size reduction for GeoJSON data\n- **Vector Tiles**: Information about pre-compressed vector tile formats\n- **Geometry Simplification**: Additional optimization through geometry simplification\n- **Point Clustering**: Reduce data size through intelligent point clustering\n\n## Implementation Guidance\n- **Client Headers**: Required Accept-Encoding headers for compression\n- **Server Response**: How server responds with compressed data\n- **Format Selection**: Choose optimal formats for different use cases\n- **Performance Impact**: Understand performance implications of compression\n\n## Optimization Strategies\n- **Data Type Optimization**: Different strategies for different data types\n- **Zoom Level Optimization**: Optimize compression based on zoom levels\n- **Layer Optimization**: Layer-specific compression recommendations\n- **Client Implementation**: Best practices for client-side implementation\n\n## Use Cases\n- **Performance Optimization**: Optimize data transfer performance\n- **Bandwidth Reduction**: Reduce bandwidth usage for mobile applications\n- **Client Implementation**: Guide client-side compression implementation\n- **System Design**: Design systems with optimal compression strategies\n\nAuthentication not required for compression information.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CompressionInfoResponse"
                }
              }
            },
            "description": "Compression information retrieved successfully"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "Get compression recommendations and information",
        "tags": [
          "Map Streaming"
        ]
      }
    },
    "/map/config": {
      "get": {
        "description": "Get Mapbox access token and configuration for map initialization.\n\n## Mapbox Configuration\nSecure token management with:\n- **Token Validation**: Automatic detection of public vs. secret tokens\n- **Security Warnings**: Alerts for improper token usage in frontend\n- **Style Options**: Multiple pre-configured map styles for different use cases\n- **Best Practices**: Security recommendations and documentation links\n- **Attribution**: Required attribution strings for legal compliance\n\n## Token Security\n- **Public Tokens (pk.*)**: Safe for frontend use, should be used for client-side applications\n- **Secret Tokens (sk.*)**: Server-side only, never expose to frontend\n- **URL Restrictions**: Enable URL restrictions in Mapbox console for production\n- **Token Rotation**: Rotate tokens periodically for security\n\n## Available Map Styles\n- **Light**: Clean, minimal style for business applications\n- **Dark**: Dark theme for night mode or modern interfaces\n- **Streets**: Detailed street map with full labeling\n- **Satellite**: Satellite imagery with street overlays\n- **Outdoors**: Optimized for outdoor and recreational use\n\n## Default Settings\n- **Center**: Tokyo coordinates (139.6917, 35.6895)\n- **Zoom**: Level 10 for city-wide view\n- **Attribution**: Includes Mapbox, OpenStreetMap, and MLIT credits\n\n## Use Cases\n- **Map Initialization**: Initialize Mapbox GL JS or React Map GL\n- **Style Selection**: Choose appropriate map style for application\n- **Security Validation**: Verify token configuration before deployment\n- **Attribution Compliance**: Ensure proper attribution display\n\nNo authentication required as this endpoint only returns public configuration data.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MapboxConfigResponse"
                }
              }
            },
            "description": "Mapbox configuration retrieved successfully"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "Get Mapbox configuration and token",
        "tags": [
          "Mapbox"
        ]
      }
    },
    "/map/coordinates-to-tiles": {
      "get": {
        "description": "Convert geographic coordinates to XYZ tile coordinates for tile-based mapping systems.\n\n## Coordinate Conversion\nPrecise tile calculation with:\n- **Web Mercator Projection**: Standard projection used by most tile systems\n- **XYZ Tile System**: Industry-standard tile coordinate system\n- **Zoom Level Support**: Support for zoom levels 0-22\n- **Bounds Calculation**: Calculate geographic bounds of the resulting tile\n- **MLIT Integration**: Example URLs for Japanese MLIT GIS API integration\n\n## Tile Coordinate System\n- **Z (Zoom)**: Zoom level from 0 (world) to 22 (building level)\n- **X (Column)**: Tile column number (west to east)\n- **Y (Row)**: Tile row number (north to south)\n- **Web Mercator**: Uses EPSG:3857 projection\n\n## Use Cases\n- **Tile Fetching**: Get tile coordinates for fetching map tiles\n- **GIS Integration**: Integrate with tile-based GIS services\n- **MLIT API**: Use with Japanese Ministry of Land, Infrastructure, Transport and Tourism APIs\n- **Cache Keys**: Generate cache keys for tile caching systems\n- **Spatial Indexing**: Create spatial indexes based on tile coordinates\n\n## Coordinate Validation\n- **Latitude Range**: -90 to 90 degrees\n- **Longitude Range**: -180 to 180 degrees\n- **Zoom Range**: 0 to 22 levels\n- **Precision**: High precision calculations for accurate tile mapping\n\n## Integration Examples\n- **MLIT GIS API**: Direct integration with Japanese government GIS services\n- **Tile Servers**: Use with any XYZ tile server\n- **Caching Systems**: Generate consistent cache keys\n- **Spatial Queries**: Enable efficient spatial data queries\n\nNo authentication required for coordinate conversion utilities.",
        "parameters": [
          {
            "description": "Latitude coordinate",
            "example": 35.6895,
            "in": "query",
            "name": "lat",
            "required": true,
            "schema": {
              "format": "double",
              "maximum": 90,
              "minimum": -90,
              "type": "number"
            }
          },
          {
            "description": "Longitude coordinate",
            "example": 139.6917,
            "in": "query",
            "name": "lng",
            "required": true,
            "schema": {
              "format": "double",
              "maximum": 180,
              "minimum": -180,
              "type": "number"
            }
          },
          {
            "description": "Zoom level (default: 13)",
            "example": 13,
            "in": "query",
            "name": "zoom",
            "required": false,
            "schema": {
              "default": 13,
              "maximum": 22,
              "minimum": 0,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CoordinatesToTilesResponse"
                }
              }
            },
            "description": "Coordinates converted to tiles successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "MISSING_COORDINATES",
                      "type": "string"
                    },
                    "message": {
                      "example": "lat and lng are required",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid coordinates or zoom level"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "Convert latitude/longitude to XYZ tile coordinates",
        "tags": [
          "Mapbox"
        ]
      }
    },
    "/map/performance-tips": {
      "get": {
        "description": "Get comprehensive performance optimization tips for both client-side and server-side implementations.\n\n## Performance Optimization Guide\nComprehensive optimization recommendations with:\n- **Client-Side Tips**: Optimization strategies for client applications\n- **Server-Side Information**: Server-side optimization details and status\n- **Layer-Specific Guidance**: Optimization recommendations for different GIS layers\n- **Implementation Examples**: Practical examples for implementing optimizations\n- **Best Practices**: Industry best practices for map performance optimization\n\n## Client-Side Optimization\n- **Batch Processing**: Use batch endpoints to reduce request count\n- **Prefetching**: Implement intelligent prefetching for smooth user experience\n- **Compression**: Enable compression for significant bandwidth savings\n- **Simplification**: Use geometry simplification at appropriate zoom levels\n- **Clustering**: Implement point clustering for dense datasets\n- **Client Caching**: Implement client-side caching strategies\n\n## Server-Side Information\n- **Cache Status**: Current server-side cache configuration and status\n- **Layer Optimization**: Different caching strategies for static vs dynamic layers\n- **TTL Configuration**: Cache TTL settings for different layer types\n- **Performance Monitoring**: Server-side performance monitoring information\n\n## Layer-Specific Recommendations\n- **Static Layers**: Optimization for rarely-changing data (use zones, schools, etc.)\n- **Dynamic Layers**: Optimization for frequently-updated data (transactions, prices)\n- **Cache Strategies**: Different caching approaches for different data types\n- **Performance Characteristics**: Understanding performance characteristics of different layers\n\n## Implementation Examples\n- **API Usage**: Practical examples of API usage for optimal performance\n- **Client Integration**: Examples of client-side integration\n- **Caching Strategies**: Implementation examples for caching\n- **Error Handling**: Best practices for error handling and fallbacks\n\n## Use Cases\n- **Performance Optimization**: Optimize existing map applications\n- **System Design**: Design new systems with optimal performance\n- **Troubleshooting**: Identify and resolve performance issues\n- **Best Practices**: Implement industry best practices\n- **Client Development**: Guide client application development\n\nAuthentication not required for performance guidance.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PerformanceTipsResponse"
                }
              }
            },
            "description": "Performance tips retrieved successfully"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "Get performance optimization tips and recommendations",
        "tags": [
          "Map Streaming"
        ]
      }
    },
    "/map/prefectures/all": {
      "get": {
        "description": "Get complete coordinate data for all 47 Japanese prefectures.\n\n## Prefecture Data\nComprehensive geographic information with:\n- **Complete Coverage**: All 47 Japanese prefectures from Hokkaido to Okinawa\n- **Accurate Coordinates**: Based on official GSI (国土地理院) geographic data\n- **Center Points**: Calculated geographic center for each prefecture\n- **Bounds**: Southwest and northeast corner coordinates for each prefecture\n- **Zoom Recommendations**: Optimal zoom levels for viewing each prefecture\n- **Bilingual Names**: Both Japanese and English prefecture names\n\n## Data Sources\n- **Official Data**: Based on Geospatial Information Authority of Japan (GSI)\n- **Accurate Bounds**: Precise geographic boundaries for each prefecture\n- **Center Calculations**: Mathematically calculated center points\n- **Zoom Optimization**: Zoom levels optimized for prefecture viewing\n\n## Use Cases\n- **Prefecture Selection**: Build prefecture selection interfaces\n- **Map Navigation**: Navigate to specific prefectures\n- **Regional Analysis**: Analyze data by prefecture\n- **Location Services**: Provide location-based services by prefecture\n- **Real Estate Applications**: Filter properties by prefecture\n\n## Prefecture Codes\n- **Format**: Two-digit codes from 01 (Hokkaido) to 47 (Okinawa)\n- **Standard**: Follows Japanese JIS X 0401 prefecture code standard\n- **Consistency**: Consistent with government and postal systems\n\nNo authentication required for geographic reference data.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PrefecturesResponse"
                }
              }
            },
            "description": "Prefecture coordinates retrieved successfully"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "Get all Japanese prefecture coordinates",
        "tags": [
          "Mapbox"
        ]
      }
    },
    "/map/prefectures/{code}/coordinates": {
      "get": {
        "description": "Get detailed coordinate information for a specific Japanese prefecture.\n\n## Prefecture Lookup\nDetailed geographic data with:\n- **Specific Prefecture**: Get data for one prefecture by code\n- **Center Coordinates**: Precise geographic center point\n- **Boundary Coordinates**: Southwest and northeast corners\n- **Optimal Zoom**: Recommended zoom level for viewing\n- **Bilingual Names**: Both Japanese and English names\n- **Map Integration**: Ready for direct use with mapping libraries\n\n## Prefecture Codes\nValid codes from 01-47:\n- **01**: 北海道 (Hokkaido)\n- **13**: 東京都 (Tokyo)\n- **27**: 大阪府 (Osaka)\n- **40**: 福岡県 (Fukuoka)\n- **47**: 沖縄県 (Okinawa)\n- And all others following JIS X 0401 standard\n\n## Use Cases\n- **Map Centering**: Center map view on specific prefecture\n- **Boundary Display**: Show prefecture boundaries on map\n- **Location Context**: Provide geographic context for addresses\n- **Regional Focus**: Focus map view on specific regions\n- **Property Filtering**: Filter real estate by prefecture\n\n## Integration\n- **Mapbox GL JS**: Use center and bounds for fitBounds()\n- **React Map GL**: Direct integration with viewport state\n- **Leaflet**: Compatible with standard coordinate formats\n- **Custom Maps**: Use with any mapping library\n\nNo authentication required for geographic reference data.",
        "parameters": [
          {
            "description": "Prefecture code (01-47)",
            "example": "13",
            "in": "path",
            "name": "code",
            "required": true,
            "schema": {
              "pattern": "^(0[1-9]|[1-4][0-7])$",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PrefectureResponse"
                }
              }
            },
            "description": "Prefecture coordinates retrieved successfully"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "PREFECTURE_NOT_FOUND",
                      "type": "string"
                    },
                    "message": {
                      "example": "Prefecture not found: 99",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Prefecture not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "Get coordinates for a specific prefecture",
        "tags": [
          "Mapbox"
        ]
      }
    },
    "/map/prefetch": {
      "post": {
        "description": "Prefetch tiles around a center point for improved user experience during map navigation.\n\n## Intelligent Prefetching\nSmart tile preloading with:\n- **Background Processing**: Tiles are fetched in the background without blocking the response\n- **Adjacent Tile Calculation**: Automatically calculate tiles around a center point\n- **Configurable Radius**: Control prefetch radius (1-2 tiles) to balance performance and bandwidth\n- **Cache Integration**: Only fetch tiles that are not already in cache\n- **Immediate Response**: Returns immediately with prefetch status information\n\n## Prefetch Strategy\n- **Viewport Prediction**: Prefetch tiles likely to be needed for panning and zooming\n- **User Behavior**: Optimize for common user navigation patterns\n- **Network Efficiency**: Batch prefetch requests to minimize network overhead\n- **Cache Warming**: Populate cache with tiles before they are needed\n\n## Performance Benefits\n- **Smooth Panning**: Eliminate loading delays when users pan the map\n- **Improved UX**: Seamless map interaction without loading indicators\n- **Bandwidth Optimization**: Prefetch only necessary tiles based on usage patterns\n- **Cache Efficiency**: Improve overall cache hit rates\n\n## Configuration Options\n- **Radius Control**: Adjust prefetch radius based on application needs\n- **Layer Selection**: Prefetch specific layers based on user context\n- **Timing Control**: Control when prefetching occurs to optimize performance\n- **Priority Management**: Prioritize prefetch requests based on likelihood of use\n\n## Use Cases\n- **Map Navigation**: Improve panning and zooming experience\n- **Real Estate Browsing**: Prefetch property data for smooth browsing\n- **Route Planning**: Prefetch tiles along planned routes\n- **Area Analysis**: Prefetch tiles for detailed area analysis\n\n## Integration\n- **Client Libraries**: Integrate with map libraries for automatic prefetching\n- **User Behavior**: Trigger prefetching based on user interaction patterns\n- **Performance Monitoring**: Monitor prefetch effectiveness and adjust strategies\n- **Cache Management**: Coordinate with cache management for optimal performance\n\nAuthentication not required for public map data access.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/PrefetchRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PrefetchResponse"
                }
              }
            },
            "description": "Prefetch initiated successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "INVALID_REQUEST",
                      "type": "string"
                    },
                    "message": {
                      "example": "apiCode and center required",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid request parameters"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "Prefetch tiles around a center point",
        "tags": [
          "Map Streaming"
        ]
      }
    },
    "/map/tiles-for-bounds": {
      "get": {
        "description": "Calculate all XYZ tiles needed to cover a specific geographic area.\n\n## Bounds to Tiles Conversion\nComprehensive tile coverage with:\n- **Area Coverage**: Calculate all tiles needed to cover a bounding box\n- **Efficient Tiling**: Minimize tile count while ensuring complete coverage\n- **Zoom Optimization**: Calculate tiles for specific zoom level\n- **Bounds Validation**: Validate geographic bounds and zoom parameters\n- **Coverage Analysis**: Provide coverage statistics and tile organization\n\n## Bounding Box Input\n- **Southwest Corner**: Bottom-left corner of the area (sw_lat, sw_lng)\n- **Northeast Corner**: Top-right corner of the area (ne_lat, ne_lng)\n- **Zoom Level**: Desired tile resolution (0-22)\n- **Validation**: Comprehensive validation of bounds and zoom\n\n## Output Information\n- **Tile Array**: Complete list of tiles covering the area\n- **Coverage Stats**: Total tiles, area coverage, tile ranges\n- **Bounds**: Each tile includes its geographic bounds\n- **Organization**: Tiles organized by X/Y ranges for efficient processing\n\n## Use Cases\n- **Viewport Loading**: Load all tiles for a map viewport\n- **Batch Processing**: Process all tiles in a geographic area\n- **Data Prefetching**: Prefetch tiles for offline use\n- **Coverage Planning**: Plan tile coverage for applications\n- **Performance Optimization**: Optimize tile loading strategies\n\n## Performance Considerations\n- **Tile Limits**: Reasonable limits to prevent excessive tile counts\n- **Zoom Validation**: Prevent overly detailed zoom levels for large areas\n- **Efficient Algorithms**: Optimized tile calculation algorithms\n- **Memory Usage**: Consider memory usage for large tile sets\n\n## Integration\n- **Batch APIs**: Use with batch tile fetching endpoints\n- **Caching Systems**: Populate tile caches efficiently\n- **Offline Maps**: Download tiles for offline map applications\n- **GIS Processing**: Process geographic data by tile regions\n\nNo authentication required for tile calculation utilities.",
        "parameters": [
          {
            "description": "Southwest latitude",
            "example": 35.65,
            "in": "query",
            "name": "sw_lat",
            "required": true,
            "schema": {
              "format": "double",
              "maximum": 90,
              "minimum": -90,
              "type": "number"
            }
          },
          {
            "description": "Southwest longitude",
            "example": 139.65,
            "in": "query",
            "name": "sw_lng",
            "required": true,
            "schema": {
              "format": "double",
              "maximum": 180,
              "minimum": -180,
              "type": "number"
            }
          },
          {
            "description": "Northeast latitude",
            "example": 35.73,
            "in": "query",
            "name": "ne_lat",
            "required": true,
            "schema": {
              "format": "double",
              "maximum": 90,
              "minimum": -90,
              "type": "number"
            }
          },
          {
            "description": "Northeast longitude",
            "example": 139.73,
            "in": "query",
            "name": "ne_lng",
            "required": true,
            "schema": {
              "format": "double",
              "maximum": 180,
              "minimum": -180,
              "type": "number"
            }
          },
          {
            "description": "Zoom level",
            "example": 13,
            "in": "query",
            "name": "zoom",
            "required": true,
            "schema": {
              "maximum": 22,
              "minimum": 0,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/TilesForBoundsResponse"
                }
              }
            },
            "description": "Tiles for bounds calculated successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "MISSING_PARAMS",
                      "type": "string"
                    },
                    "message": {
                      "example": "sw_lat, sw_lng, ne_lat, ne_lng, zoom are required",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid bounds or zoom level"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "Get tiles covering a geographic bounding box",
        "tags": [
          "Mapbox"
        ]
      }
    },
    "/map/tiles-to-bounds": {
      "get": {
        "description": "Convert XYZ tile coordinates back to geographic latitude/longitude bounds.\n\n## Reverse Tile Conversion\nPrecise bounds calculation with:\n- **Tile to Geographic**: Convert tile coordinates to lat/lng bounds\n- **Bounds Calculation**: Calculate southwest and northeast corners\n- **Center Point**: Calculate center coordinates of the tile\n- **Web Mercator**: Inverse projection from tile system to geographic coordinates\n- **High Precision**: Accurate coordinate calculations for mapping applications\n\n## Tile Coordinate Input\n- **Z (Zoom)**: Zoom level (0-22)\n- **X (Column)**: Tile column number\n- **Y (Row)**: Tile row number\n- **Validation**: Comprehensive validation of tile coordinates\n\n## Output Data\n- **Bounds**: Southwest and northeast corner coordinates\n- **Center**: Calculated center point of the tile\n- **Tile Info**: Original tile coordinates for reference\n- **Geographic Precision**: High-precision coordinate calculations\n\n## Use Cases\n- **Tile Bounds Display**: Show the geographic area covered by a tile\n- **Spatial Queries**: Query data within tile boundaries\n- **Map Viewport**: Set map viewport to tile bounds\n- **Data Validation**: Validate that data falls within expected tile bounds\n- **Tile Coverage**: Calculate geographic coverage of tile sets\n\n## Integration\n- **Mapping Libraries**: Use bounds with fitBounds() methods\n- **Spatial Databases**: Query geographic databases with calculated bounds\n- **GIS Applications**: Integrate with GIS systems for spatial analysis\n- **Data Visualization**: Visualize tile coverage on maps\n\nNo authentication required for coordinate conversion utilities.",
        "parameters": [
          {
            "description": "Zoom level",
            "example": 13,
            "in": "query",
            "name": "z",
            "required": true,
            "schema": {
              "maximum": 22,
              "minimum": 0,
              "type": "integer"
            }
          },
          {
            "description": "Tile X coordinate",
            "example": 7274,
            "in": "query",
            "name": "x",
            "required": true,
            "schema": {
              "minimum": 0,
              "type": "integer"
            }
          },
          {
            "description": "Tile Y coordinate",
            "example": 3225,
            "in": "query",
            "name": "y",
            "required": true,
            "schema": {
              "minimum": 0,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/TilesToBoundsResponse"
                }
              }
            },
            "description": "Tile coordinates converted to bounds successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "MISSING_PARAMS",
                      "type": "string"
                    },
                    "message": {
                      "example": "z, x, and y are required",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid tile coordinates"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "Convert XYZ tile coordinates to geographic bounds",
        "tags": [
          "Mapbox"
        ]
      }
    },
    "/map/viewport-tiles": {
      "get": {
        "description": "Calculate and return information about all tiles needed to display a specific map viewport.\n\n## Viewport Tile Analysis\nComprehensive viewport coverage with:\n- **Complete Coverage**: Calculate all tiles needed to cover the viewport bounds\n- **Cache Status**: Check cache status for each required tile\n- **Performance Metrics**: Provide cache hit statistics for optimization\n- **Bounds Validation**: Validate viewport bounds and zoom parameters\n- **Tile Limits**: Prevent excessive tile counts that could impact performance\n\n## Viewport Information\n- **Tile Calculation**: Precise calculation of tiles needed for viewport coverage\n- **Cache Analysis**: Detailed cache status for each tile\n- **Performance Data**: Hit counts and cache efficiency metrics\n- **Coverage Statistics**: Total tiles, cached tiles, and coverage analysis\n\n## Performance Optimization\n- **Cache Efficiency**: Identify cache misses for optimization opportunities\n- **Prefetch Planning**: Use tile information for intelligent prefetching\n- **Load Balancing**: Distribute tile requests efficiently\n- **Memory Management**: Monitor tile count to prevent memory issues\n\n## Use Cases\n- **Viewport Planning**: Plan tile loading strategy for map viewports\n- **Cache Analysis**: Analyze cache performance for specific areas\n- **Performance Monitoring**: Monitor tile loading performance\n- **Optimization**: Identify opportunities for performance improvements\n- **Prefetch Strategy**: Plan prefetching based on viewport analysis\n\n## Integration\n- **Map Libraries**: Use with mapping libraries for viewport management\n- **Performance Monitoring**: Integrate with performance monitoring systems\n- **Cache Management**: Coordinate with cache management strategies\n- **Load Planning**: Plan tile loading based on viewport requirements\n\n## Limitations\n- **Tile Count Limits**: Maximum 50 tiles per viewport to prevent performance issues\n- **Zoom Restrictions**: Reasonable zoom level limits for large areas\n- **Bounds Validation**: Comprehensive validation of geographic bounds\n\nAuthentication not required for viewport analysis.",
        "parameters": [
          {
            "description": "Southwest latitude of viewport",
            "example": 35.65,
            "in": "query",
            "name": "sw_lat",
            "required": true,
            "schema": {
              "format": "double",
              "maximum": 90,
              "minimum": -90,
              "type": "number"
            }
          },
          {
            "description": "Southwest longitude of viewport",
            "example": 139.65,
            "in": "query",
            "name": "sw_lng",
            "required": true,
            "schema": {
              "format": "double",
              "maximum": 180,
              "minimum": -180,
              "type": "number"
            }
          },
          {
            "description": "Northeast latitude of viewport",
            "example": 35.73,
            "in": "query",
            "name": "ne_lat",
            "required": true,
            "schema": {
              "format": "double",
              "maximum": 90,
              "minimum": -90,
              "type": "number"
            }
          },
          {
            "description": "Northeast longitude of viewport",
            "example": 139.73,
            "in": "query",
            "name": "ne_lng",
            "required": true,
            "schema": {
              "format": "double",
              "maximum": 180,
              "minimum": -180,
              "type": "number"
            }
          },
          {
            "description": "Zoom level",
            "example": 13,
            "in": "query",
            "name": "zoom",
            "required": true,
            "schema": {
              "maximum": 22,
              "minimum": 0,
              "type": "integer"
            }
          },
          {
            "description": "GIS layer code for cache analysis",
            "example": "XKT002",
            "in": "query",
            "name": "apiCode",
            "required": false,
            "schema": {
              "$ref": "#/components/schemas/MLITGISAPICode"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ViewportTilesResponse"
                }
              }
            },
            "description": "Viewport tiles calculated successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "INVALID_REQUEST",
                      "type": "string"
                    },
                    "message": {
                      "example": "sw_lat, sw_lng, ne_lat, ne_lng, zoom required",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid viewport parameters"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "Get all tiles needed for a map viewport",
        "tags": [
          "Map Streaming"
        ]
      }
    },
    "/mcp": {
      "post": {
        "description": "\nJSON-RPC 2.0 over MCP Streamable HTTP. Stateless: no `Mcp-Session-Id`, and responses are `application/json`, never an SSE stream. GET and DELETE answer 405.\n\n**Auth:** `Authorization: Bearer <token>` only — never a cookie. The token must be issued by this project's Supabase OAuth 2.1 server to a client (`client_id` claim); a browser session token is refused. Without a valid token the answer is 401 with `WWW-Authenticate: Bearer resource_metadata=\"…/api/.well-known/oauth-protected-resource\", scope=\"openid email profile\"`.\n\n**Tools** (all `readOnlyHint: true`; discover them with `tools/list`): sbc_whoami, sbc_list_deadlines, sbc_get_deadline_guidance, sbc_get_consumption_tax_period, sbc_get_filing_procedure, sbc_check_form_values, sbc_list_unbooked_bank_rows, sbc_get_bank_row_context, sbc_draft_gov_inquiry.\n\n**Rate limit:** 300 calls / 15 min per user (`mcp` policy).\n      ",
        "operationId": "postMcp",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/McpJsonRpcRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/McpJsonRpcResponse"
                }
              }
            },
            "description": "JSON-RPC response (a tool failure is `result.isError: true`, not an HTTP error)"
          },
          "202": {
            "description": "Accepted (a notification; no body)"
          },
          "401": {
            "description": "Missing or invalid token; see WWW-Authenticate"
          },
          "405": {
            "description": "Only POST is served"
          },
          "429": {
            "description": "Rate limit exceeded"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "MCP Streamable HTTP endpoint (stateless, JSON responses)",
        "tags": [
          "MCP Connector"
        ]
      }
    },
    "/members": {
      "get": {
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                }
              }
            },
            "description": "Members and pending invites"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List members and pending invites for the active account",
        "tags": [
          "Team Members"
        ]
      }
    },
    "/members/accept/{token}": {
      "post": {
        "description": "Accepts a pending invite. The authenticated user's email must match the invited email.",
        "parameters": [
          {
            "description": "Invite token from the accept URL",
            "in": "path",
            "name": "token",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                }
              }
            },
            "description": "Invite accepted; membership activated"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "description": "Invite email does not match the authenticated user"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Accept a team invite",
        "tags": [
          "Team Members"
        ]
      }
    },
    "/members/invite": {
      "post": {
        "description": "Creates a pending invite and returns a copyable accept URL. Consumes one seat from the quota.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/MemberInviteRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MemberInviteCreated"
                }
              }
            },
            "description": "Invite created"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "429": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetails"
                }
              }
            },
            "description": "Seat limit reached for the current plan"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Invite a team member (admin/owner only)",
        "tags": [
          "Team Members"
        ]
      }
    },
    "/members/my-accounts": {
      "get": {
        "description": "Returns the actor's own account (role \"owner\") plus every owner account where they hold an active, non-revoked membership. Data source for the frontend active-account selector. UI-only — never a trust boundary; membership is re-checked per request.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MyAccountsResponse"
                }
              }
            },
            "description": "Accounts the actor may act inside"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Accounts the current user can act inside (account switcher)",
        "tags": [
          "Team Members"
        ]
      }
    },
    "/members/{memberId}": {
      "delete": {
        "parameters": [
          {
            "description": "account_members row id (or member_invites id for pending invites)",
            "in": "path",
            "name": "memberId",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Member/invite revoked"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Revoke a member or pending invite (admin/owner only)",
        "tags": [
          "Team Members"
        ]
      }
    },
    "/members/{memberId}/role": {
      "put": {
        "parameters": [
          {
            "description": "account_members row id (or member_invites id for pending invites)",
            "in": "path",
            "name": "memberId",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/MemberRoleRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                }
              }
            },
            "description": "Role updated"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Change a member or invite role (admin/owner only)",
        "tags": [
          "Team Members"
        ]
      }
    },
    "/money-trail": {
      "get": {
        "description": "Walks the caller’s link tables (document relationships, document_expenses, file / bank / 仕訳 evidence, transaction links) out from the origin, at most 5 hops and 40 records. A claim is paid by the same rule as the 経費精算 page; a 合算精算 支払明細書 never marks a claim paid by its own bank link.",
        "parameters": [
          {
            "in": "query",
            "name": "kind",
            "required": true,
            "schema": {
              "enum": [
                "file",
                "document",
                "bank_transaction",
                "expense"
              ],
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/MoneyTrail"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "The trail"
          },
          "400": {
            "description": "Validation error (RFC 9457)"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Not the caller’s record, or deleted / voided (RFC 9457)"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "The chain of linked records around one record, and whether it was paid",
        "tags": [
          "Money trail"
        ]
      }
    },
    "/multi-office/apportion": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/MultiOfficeApportionRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                }
              }
            },
            "description": "Apportionment result"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Apportion 法人税割 across offices by employee headcount",
        "tags": [
          "Multi-Office"
        ]
      }
    },
    "/multi-office/context-facts": {
      "get": {
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                }
              }
            },
            "description": "Context facts"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List saved context Q&A facts",
        "tags": [
          "Multi-Office"
        ]
      },
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/MultiOfficeContextFactRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                }
              }
            },
            "description": "回答を記録しました"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Save a context Q&A fact",
        "tags": [
          "Multi-Office"
        ]
      }
    },
    "/multi-office/offices": {
      "get": {
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                }
              }
            },
            "description": "Office list"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List registered offices",
        "tags": [
          "Multi-Office"
        ]
      },
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/MultiOfficeCreateRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "office": {
                          "$ref": "#/components/schemas/MultiOfficeSavedOffice"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "事業所を登録しました。申告カレンダーを再計算し、この事業所で発生する手続きを返します。"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Register a new office",
        "tags": [
          "Multi-Office"
        ]
      }
    },
    "/multi-office/offices/{office_id}": {
      "patch": {
        "parameters": [
          {
            "description": "事業所 id",
            "in": "path",
            "name": "office_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/MultiOfficeUpdateRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "office": {
                          "$ref": "#/components/schemas/MultiOfficeSavedOffice"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "事業所情報を更新しました。申告カレンダーを再計算し、この事業所で発生する手続きを返します。"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update an office",
        "tags": [
          "Multi-Office"
        ]
      }
    },
    "/multi-office/offices/{office_id}/filing-progress": {
      "patch": {
        "parameters": [
          {
            "description": "事業所 id",
            "in": "path",
            "name": "office_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/MultiOfficeFilingProgressRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                }
              }
            },
            "description": "ステータスを更新しました"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update 届出 filing-progress step status",
        "tags": [
          "Multi-Office"
        ]
      }
    },
    "/multi-office/payment-schedule": {
      "get": {
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                }
              }
            },
            "description": "Payment schedule"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Computed 納付 schedule across offices",
        "tags": [
          "Multi-Office"
        ]
      }
    },
    "/multi-office/payments": {
      "get": {
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                }
              }
            },
            "description": "Payment records"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List 納付記録",
        "tags": [
          "Multi-Office"
        ]
      },
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/MultiOfficeCreatePaymentRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                }
              }
            },
            "description": "納付記録を作成しました"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create a 納付記録",
        "tags": [
          "Multi-Office"
        ]
      }
    },
    "/multi-office/payments/bank-candidates": {
      "get": {
        "parameters": [
          {
            "description": "Amount (円) to match against bank transactions",
            "in": "query",
            "name": "amountYen",
            "required": false,
            "schema": {
              "maximum": 1000000000,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                }
              }
            },
            "description": "Candidate bank transactions"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Suggest matching bank transactions for a payment amount",
        "tags": [
          "Multi-Office"
        ]
      }
    },
    "/multi-office/payments/{payment_id}": {
      "delete": {
        "parameters": [
          {
            "description": "納付記録 id",
            "in": "path",
            "name": "payment_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                }
              }
            },
            "description": "納付記録を削除しました"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Delete a 納付記録",
        "tags": [
          "Multi-Office"
        ]
      },
      "patch": {
        "parameters": [
          {
            "description": "納付記録 id",
            "in": "path",
            "name": "payment_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/MultiOfficeUpdatePaymentRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                }
              }
            },
            "description": "納付記録を更新しました"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update a 納付記録 (amount, due/paid date, bank link, memo)",
        "tags": [
          "Multi-Office"
        ]
      }
    },
    "/multi-office/simulate": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/MultiOfficeSimulateRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                }
              }
            },
            "description": "Simulation result"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Simulate 均等割 for a hypothetical office location",
        "tags": [
          "Multi-Office"
        ]
      }
    },
    "/mushi-tunnel/{path}": {
      "get": {
        "description": "Unauthenticated. Path after `/api/mushi-tunnel` must start with `/v1/`. Rate-limited. No request body.",
        "parameters": [
          {
            "in": "path",
            "name": "path",
            "required": true,
            "schema": {
              "example": "v1/reports",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Upstream accepted (or mirrored upstream 2xx)"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MushiTunnelError"
                }
              }
            },
            "description": "Rejected (allowlist / path / method)"
          },
          "413": {
            "description": "Body exceeds 1 MB"
          },
          "429": {
            "description": "Rate limited"
          },
          "502": {
            "description": "Upstream Mushi ingest unreachable"
          },
          "503": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MushiTunnelError"
                }
              }
            },
            "description": "Tunnel not configured (empty project allowlist)"
          }
        },
        "security": [],
        "summary": "Forward a browser Mushi read to allowlisted upstream, e.g. v1/sdk/latest-version",
        "tags": [
          "Mushi Tunnel"
        ]
      },
      "patch": {
        "description": "Unauthenticated. Path after `/api/mushi-tunnel` must start with `/v1/`. CSRF skipped. Rate-limited. Max 1 MB. Optional beacon envelope `{ mushiBeacon: true, path, headers, body }` for sendBeacon (headers cannot be set on beacon). GET, POST, PUT and PATCH are forwarded; other methods get 400 `method_not_allowed`.",
        "parameters": [
          {
            "in": "path",
            "name": "path",
            "required": true,
            "schema": {
              "example": "v1/reports",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "additionalProperties": true,
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Upstream accepted (or mirrored upstream 2xx)"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MushiTunnelError"
                }
              }
            },
            "description": "Rejected (allowlist / path / method)"
          },
          "413": {
            "description": "Body exceeds 1 MB"
          },
          "429": {
            "description": "Rate limited"
          },
          "502": {
            "description": "Upstream Mushi ingest unreachable"
          },
          "503": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MushiTunnelError"
                }
              }
            },
            "description": "Tunnel not configured (empty project allowlist)"
          }
        },
        "security": [],
        "summary": "Forward a browser Mushi PATCH to allowlisted upstream",
        "tags": [
          "Mushi Tunnel"
        ]
      },
      "post": {
        "description": "Unauthenticated. Path after `/api/mushi-tunnel` must start with `/v1/`. CSRF skipped. Rate-limited. Max 1 MB. Optional beacon envelope `{ mushiBeacon: true, path, headers, body }` for sendBeacon (headers cannot be set on beacon). GET, POST, PUT and PATCH are forwarded; other methods get 400 `method_not_allowed`.",
        "parameters": [
          {
            "in": "path",
            "name": "path",
            "required": true,
            "schema": {
              "example": "v1/reports",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "additionalProperties": true,
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Upstream accepted (or mirrored upstream 2xx)"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MushiTunnelError"
                }
              }
            },
            "description": "Rejected (allowlist / path / method)"
          },
          "413": {
            "description": "Body exceeds 1 MB"
          },
          "429": {
            "description": "Rate limited"
          },
          "502": {
            "description": "Upstream Mushi ingest unreachable"
          },
          "503": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MushiTunnelError"
                }
              }
            },
            "description": "Tunnel not configured (empty project allowlist)"
          }
        },
        "security": [],
        "summary": "Forward a browser Mushi ingest call to allowlisted upstream",
        "tags": [
          "Mushi Tunnel"
        ]
      },
      "put": {
        "description": "Unauthenticated. Path after `/api/mushi-tunnel` must start with `/v1/`. CSRF skipped. Rate-limited. Max 1 MB. Optional beacon envelope `{ mushiBeacon: true, path, headers, body }` for sendBeacon (headers cannot be set on beacon). GET, POST, PUT and PATCH are forwarded; other methods get 400 `method_not_allowed`.",
        "parameters": [
          {
            "in": "path",
            "name": "path",
            "required": true,
            "schema": {
              "example": "v1/reports",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "additionalProperties": true,
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Upstream accepted (or mirrored upstream 2xx)"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MushiTunnelError"
                }
              }
            },
            "description": "Rejected (allowlist / path / method)"
          },
          "413": {
            "description": "Body exceeds 1 MB"
          },
          "429": {
            "description": "Rate limited"
          },
          "502": {
            "description": "Upstream Mushi ingest unreachable"
          },
          "503": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MushiTunnelError"
                }
              }
            },
            "description": "Tunnel not configured (empty project allowlist)"
          }
        },
        "security": [],
        "summary": "Forward a browser Mushi PUT to allowlisted upstream",
        "tags": [
          "Mushi Tunnel"
        ]
      }
    },
    "/notice-documents/status": {
      "patch": {
        "description": "Each notice keeps the single-notice timestamp rules: `read_at` is stamped on its first move off 未読, `handled_at` on its first 対応済 / アーカイブ; a step back clears neither. Ids that are not the caller’s, or are deleted, are skipped and listed in `skippedIds`.",
        "operationId": "bulkUpdateNoticeStatus",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "additionalProperties": false,
                "properties": {
                  "ids": {
                    "items": {
                      "format": "uuid",
                      "type": "string"
                    },
                    "maxItems": 200,
                    "minItems": 1,
                    "type": "array",
                    "uniqueItems": true
                  },
                  "status": {
                    "enum": [
                      "unread",
                      "read",
                      "in_progress",
                      "completed",
                      "archived"
                    ],
                    "type": "string"
                  }
                },
                "required": [
                  "ids",
                  "status"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/NoticeBulkStatusResponse"
                }
              }
            },
            "description": "Statuses set"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Set one status on many notices (すべて既読 / a selection)",
        "tags": [
          "Notice Documents"
        ]
      }
    },
    "/notice-documents/{id}/history": {
      "get": {
        "description": "Pairs by the same issuer, the same kind (the title without its period) and a parsed period (the CSV’s 納付目的年月, else the title’s 令和N年M月分). Read-only.",
        "operationId": "getNoticeHistory",
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Periods in the window, this one included",
            "in": "query",
            "name": "months",
            "required": false,
            "schema": {
              "default": 6,
              "maximum": 12,
              "minimum": 2,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/NoticeHistoryResponse"
                }
              }
            },
            "description": "History"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "The same notice’s other periods — for 前月比 and the recent trend",
        "tags": [
          "Notice Documents"
        ]
      }
    },
    "/notifications": {
      "get": {
        "description": "Retrieve paginated list of notifications for the authenticated user with comprehensive filtering options.\n\n## User Notifications (ユーザー通知)\nComprehensive notification management with:\n- **Multi-Type Support**: Success, error, warning, and info notifications\n- **Category Filtering**: Filter by system, message, task, friend, document, expense, project, travel\n- **Priority Levels**: Low, medium, high, and urgent priority notifications\n- **Read Status Tracking**: Track read/unread status with detailed interaction analytics\n- **Pagination Support**: Efficient navigation through large notification lists\n- **Real-Time Updates**: Integration with WebSocket/SSE for real-time notification delivery\n\n## Notification Categories\n- **System**: System-generated notifications and alerts\n- **Message**: Direct messages and communication notifications\n- **Task**: Task-related notifications and updates\n- **Friend**: Social and collaboration notifications\n- **Document**: Document-related notifications and reviews\n- **Expense**: Expense and financial notifications\n- **Project**: Project management and milestone notifications\n- **Travel**: Travel and reimbursement notifications\n\n## Priority Levels\n- **Urgent**: Critical notifications requiring immediate attention\n- **High**: Important notifications requiring prompt attention\n- **Medium**: Standard notifications for regular review\n- **Low**: Informational notifications for awareness\n\n## Filtering Options\n- **Type Filter**: Filter by notification type (success, error, warning, info)\n- **Category Filter**: Filter by notification category\n- **Read Status**: Filter by read/unread status\n- **Pagination**: Configurable page size and navigation\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Page number for pagination",
            "in": "query",
            "name": "page_number",
            "required": false,
            "schema": {
              "default": 1,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "description": "Number of notifications per page",
            "in": "query",
            "name": "page_size",
            "required": false,
            "schema": {
              "default": 20,
              "maximum": 100,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "description": "Filter by notification type",
            "in": "query",
            "name": "type",
            "required": false,
            "schema": {
              "$ref": "#/components/schemas/NotificationType"
            }
          },
          {
            "description": "Filter by notification category",
            "in": "query",
            "name": "category",
            "required": false,
            "schema": {
              "$ref": "#/components/schemas/NotificationCategory"
            }
          },
          {
            "description": "Filter by read status (true for unread only)",
            "in": "query",
            "name": "is_unread",
            "required": false,
            "schema": {
              "type": "boolean"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "user_notifications": {
                    "summary": "User notifications with various types and priorities",
                    "value": {
                      "data": {
                        "items": [
                          {
                            "actions": [
                              {
                                "action": "view_document",
                                "label": "Review Document",
                                "url": "/documents/123"
                              }
                            ],
                            "category": "document",
                            "click_action": null,
                            "clicked_at": null,
                            "created_at": "2024-01-15T10:30:00.000Z",
                            "data": {
                              "deadline": "2024-01-20",
                              "documentType": "report"
                            },
                            "dismissed_at": null,
                            "externalUrl": null,
                            "id": "123e4567-e89b-12d3-a456-426614174000",
                            "is_clicked": false,
                            "is_dismissed": false,
                            "is_read": false,
                            "message": "Please review the quarterly report document.",
                            "priority": "high",
                            "read_at": null,
                            "read_method": null,
                            "relatedIds": {
                              "documentId": "456e7890-f12a-34b5-c678-901234567890"
                            },
                            "sender": {
                              "id": "system",
                              "name": "Document System"
                            },
                            "title": "Document Review Required",
                            "type": "info",
                            "updated_at": "2024-01-15T10:30:00.000Z",
                            "url": "/documents/123",
                            "user_id": "abc12345-def6-7890-ghij-klmnopqrstuv"
                          }
                        ],
                        "pagination": {
                          "currentPage": 1,
                          "hasNext": true,
                          "hasPrevious": false,
                          "pageSize": 20,
                          "totalItems": 25,
                          "totalPages": 2
                        },
                        "unreadCount": 5
                      },
                      "message": "Notifications retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/NotificationListResponse"
                }
              }
            },
            "description": "Notifications retrieved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get user notifications",
        "tags": [
          "Notifications"
        ]
      },
      "post": {
        "description": "Create a new notification for specified recipients with comprehensive delivery options.\n\n## Notification Creation (通知作成)\nAdvanced notification creation with:\n- **Multi-Recipient Support**: Send to multiple users in a single request\n- **Rich Content**: Support for actions, links, and structured data\n- **Delivery Options**: Configure web, push, and email delivery channels\n- **Scheduling Support**: Schedule notifications for future delivery\n- **Priority Management**: Set priority levels for proper notification handling\n- **Tracking Options**: Enable delivery and interaction tracking\n\n## Content Features\n- **Rich Actions**: Add interactive buttons with custom actions\n- **Related Entities**: Link notifications to tasks, projects, documents, etc.\n- **Custom Data**: Include custom data for application-specific handling\n- **URLs and Links**: Support for internal and external navigation\n- **Sender Information**: Customize sender details and avatar\n\n## Delivery Channels\n- **Web**: In-app notifications with real-time delivery\n- **Push**: Browser and mobile push notifications\n- **Email**: Email notifications with rich content\n- **Scheduling**: Schedule notifications for future delivery\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "document_review": {
                  "summary": "Document review notification",
                  "value": {
                    "notification": {
                      "actions": [
                        {
                          "action": "view_document",
                          "label": "Review Document",
                          "url": "/documents/123"
                        },
                        {
                          "action": "mark_reviewed",
                          "label": "Mark as Reviewed"
                        }
                      ],
                      "category": "document",
                      "data": {
                        "deadline": "2024-01-20",
                        "documentType": "report"
                      },
                      "delivery": {
                        "email": false,
                        "push": true,
                        "web": true
                      },
                      "message": "Please review the quarterly report document by January 20th.",
                      "priority": "high",
                      "relatedIds": {
                        "documentId": "456e7890-f12a-34b5-c678-901234567890"
                      },
                      "title": "Document Review Required",
                      "type": "info",
                      "url": "/documents/123"
                    },
                    "options": {
                      "sendImmediate": true,
                      "trackDelivery": true
                    },
                    "recipients": [
                      "abc12345-def6-7890-ghij-klmnopqrstuv",
                      "def67890-abc1-2345-6789-0123456789ab"
                    ]
                  }
                },
                "system_alert": {
                  "summary": "System alert notification",
                  "value": {
                    "notification": {
                      "category": "system",
                      "delivery": {
                        "email": true,
                        "push": true,
                        "web": true
                      },
                      "message": "System maintenance is scheduled for tonight at 2:00 AM JST.",
                      "priority": "medium",
                      "scheduling": {
                        "scheduleAt": "2024-01-15T08:00:00.000Z"
                      },
                      "title": "System Maintenance Scheduled",
                      "type": "warning"
                    },
                    "recipients": [
                      "abc12345-def6-7890-ghij-klmnopqrstuv"
                    ]
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/CreateNotificationRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/NotificationResponse"
                }
              }
            },
            "description": "Notification created successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create notification",
        "tags": [
          "Notifications"
        ]
      }
    },
    "/notifications/delivery-confirm": {
      "post": {
        "description": "Confirm successful delivery of notifications for reliability tracking.\n\n## Delivery Confirmation (配信確認)\nReliable delivery tracking with:\n- **Delivery Verification**: Confirm notifications were successfully delivered\n- **Reliability Metrics**: Track delivery success rates and failures\n- **Retry Logic**: Support for retry mechanisms on delivery failures\n- **Analytics**: Comprehensive delivery analytics and reporting\n- **Quality Assurance**: Ensure notification delivery quality and reliability\n\n## Confirmation Process\n- **Client Confirmation**: Client confirms receipt of notifications\n- **Server Tracking**: Server tracks delivery confirmation status\n- **Retry Management**: Handle failed deliveries with retry logic\n- **Analytics Update**: Update delivery analytics and metrics\n- **Quality Monitoring**: Monitor delivery quality and performance\n\n## Use Cases\n- **Reliability**: Ensure critical notifications are delivered\n- **Analytics**: Track notification delivery performance\n- **Quality Assurance**: Monitor and improve delivery reliability\n- **Troubleshooting**: Diagnose delivery issues and failures\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "deliveryMethod": {
                    "description": "Method used for delivery",
                    "enum": [
                      "web",
                      "push",
                      "email",
                      "mobile"
                    ],
                    "type": "string"
                  },
                  "deviceInfo": {
                    "$ref": "#/components/schemas/DeviceInfo"
                  },
                  "notificationIds": {
                    "description": "Array of notification IDs to confirm delivery",
                    "items": {
                      "format": "uuid",
                      "type": "string"
                    },
                    "maxItems": 50,
                    "minItems": 1,
                    "type": "array"
                  }
                },
                "required": [
                  "notificationIds",
                  "deliveryMethod"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "confirmedCount": {
                          "example": 5,
                          "type": "integer"
                        },
                        "failedCount": {
                          "example": 0,
                          "type": "integer"
                        },
                        "success": {
                          "example": true,
                          "type": "boolean"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Delivery confirmation processed successfully",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Delivery confirmation processed successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Confirm notification delivery",
        "tags": [
          "Notifications"
        ]
      }
    },
    "/notifications/push/subscribe": {
      "post": {
        "description": "Register user device for push notification delivery.\n\n## Push Subscription (プッシュ通知登録)\nDevice registration with:\n- **Multi-Device Support**: Support for multiple devices per user\n- **Browser Compatibility**: Compatible with all major browsers\n- **Device Information**: Track device type, platform, and capabilities\n- **Subscription Management**: Automatic handling of subscription updates\n- **Security**: Secure subscription storage and management\n\n## Subscription Process\n- **Client Registration**: Client generates push subscription using VAPID key\n- **Server Storage**: Server stores subscription for future push delivery\n- **Device Tracking**: Track device information for analytics and troubleshooting\n- **Subscription Updates**: Handle subscription changes and renewals\n- **Error Handling**: Comprehensive error handling for subscription failures\n\n## Device Support\n- **Web Browsers**: Chrome, Firefox, Safari, Edge with push support\n- **Mobile Web**: Mobile browsers with push notification support\n- **PWA**: Progressive Web Apps with full push notification support\n- **Desktop**: Desktop browsers with notification permissions\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "web_subscription": {
                  "summary": "Web browser push subscription",
                  "value": {
                    "deviceInfo": {
                      "browser": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
                      "platform": "web",
                      "version": "1.0.0"
                    },
                    "subscription": {
                      "endpoint": "https://fcm.googleapis.com/fcm/send/abc123",
                      "keys": {
                        "auth": "tBHItJI5svbpez7KI4CCXg",
                        "p256dh": "BEl62iUYgUivxIkv69yViEuiBIa-Ib9-SkvMeAtA3LFw"
                      }
                    }
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/PushSubscribeRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PushSubscriptionResponse"
                }
              }
            },
            "description": "Successfully subscribed to push notifications"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Subscribe to push notifications",
        "tags": [
          "Notifications"
        ]
      }
    },
    "/notifications/push/unsubscribe": {
      "post": {
        "description": "Unregister user device from push notification delivery.\n\n## Push Unsubscription (プッシュ通知解除)\nDevice unregistration with:\n- **Clean Unsubscription**: Properly remove device from push delivery\n- **Subscription Cleanup**: Clean up stored subscription data\n- **Privacy Compliance**: Ensure user privacy and data protection\n- **Error Handling**: Handle unsubscription errors gracefully\n- **Analytics Tracking**: Track unsubscription for user behavior analysis\n\n## Unsubscription Process\n- **Client Request**: Client requests unsubscription from push notifications\n- **Server Cleanup**: Server removes subscription from storage\n- **Service Cleanup**: Clean up push service registrations\n- **Confirmation**: Confirm successful unsubscription to client\n- **Analytics**: Track unsubscription events for analysis\n\n## Use Cases\n- **User Preference**: User chooses to disable push notifications\n- **Device Change**: User switches devices and needs to clean up old subscriptions\n- **Privacy**: User requests removal of push notification data\n- **Troubleshooting**: Clean up problematic subscriptions\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "deviceInfo": {
                    "$ref": "#/components/schemas/DeviceInfo"
                  },
                  "subscriptionId": {
                    "description": "Specific subscription ID to unsubscribe (optional)",
                    "format": "uuid",
                    "type": "string"
                  }
                },
                "type": "object"
              }
            }
          },
          "required": false
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "success": {
                          "example": true,
                          "type": "boolean"
                        },
                        "unsubscribedCount": {
                          "example": 1,
                          "type": "integer"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Successfully unsubscribed from push notifications",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Successfully unsubscribed from push notifications"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Unsubscribe from push notifications",
        "tags": [
          "Notifications"
        ]
      }
    },
    "/notifications/push/vapid-public-key": {
      "get": {
        "description": "Retrieve the VAPID public key required for push notification setup.\n\n## VAPID Key (VAPID公開鍵)\nSecure push notification setup with:\n- **Web Push Protocol**: Standard VAPID key for web push notifications\n- **Security**: Secure authentication for push notification services\n- **Browser Compatibility**: Compatible with all major browsers supporting push notifications\n- **Service Worker**: Required for service worker push notification registration\n- **Cross-Platform**: Works across web, PWA, and mobile web applications\n\n## VAPID (Voluntary Application Server Identification)\n- **Authentication**: Authenticates your server with push services\n- **Security**: Prevents unauthorized push notification sending\n- **Standards Compliance**: Follows web push protocol standards\n- **Browser Support**: Supported by Chrome, Firefox, Safari, Edge\n- **Service Integration**: Required for FCM, Mozilla Push, and other services\n\n## Use Cases\n- **Push Notification Setup**: Required for initial push notification setup\n- **Service Worker Registration**: Used in service worker for push subscription\n- **Client-Side Integration**: Required for frontend push notification implementation\n- **Cross-Browser Support**: Ensures compatibility across different browsers\n\n## Authentication\nNo authentication required - public endpoint for client-side integration.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/VapidKeyResponse"
                }
              }
            },
            "description": "VAPID public key retrieved successfully"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "Get VAPID public key",
        "tags": [
          "Notifications"
        ]
      }
    },
    "/notifications/read-all": {
      "put": {
        "description": "Mark all unread notifications as read for the authenticated user.\n\n## Mark All as Read (全て既読にする)\nBulk read operation with:\n- **Batch Processing**: Efficiently mark multiple notifications as read\n- **Performance Optimized**: Optimized database operations for bulk updates\n- **User Experience**: Quick way to clear all unread notifications\n- **Analytics Tracking**: Track bulk read operations for user behavior analysis\n- **Method Recording**: Record the method used for bulk read operation\n\n## Use Cases\n- **Notification Cleanup**: Quick way to clear notification backlog\n- **User Experience**: Reduce notification overwhelm\n- **Mobile Integration**: Efficient bulk operations for mobile apps\n- **Dashboard Management**: Clear notification badges and indicators\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "description": "Use camelCase for all fields",
                "properties": {
                  "readMethod": {
                    "$ref": "#/components/schemas/ReadMethod"
                  }
                },
                "type": "object"
              }
            }
          },
          "required": false
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "success": {
                          "example": true,
                          "type": "boolean"
                        },
                        "updatedCount": {
                          "example": 12,
                          "type": "integer"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "All notifications marked as read successfully",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "All notifications marked as read successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Mark all notifications as read",
        "tags": [
          "Notifications"
        ]
      }
    },
    "/notifications/unread-count": {
      "get": {
        "description": "Get the count of unread notifications for the authenticated user.\n\n## Unread Count (未読数)\nReal-time unread notification tracking with:\n- **Real-Time Updates**: Live count updates via WebSocket/SSE\n- **Performance Optimized**: Efficient counting without full notification retrieval\n- **Dashboard Integration**: Perfect for dashboard badges and indicators\n- **User Experience**: Immediate feedback on notification status\n- **Lightweight Response**: Minimal data transfer for frequent polling\n\n## Use Cases\n- **Dashboard Badges**: Display unread count in navigation badges\n- **Real-Time Updates**: Update counts as notifications are read\n- **Mobile Integration**: Efficient count retrieval for mobile apps\n- **Performance Monitoring**: Track user engagement with notifications\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/UnreadCountResponse"
                }
              }
            },
            "description": "Unread count retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get unread notification count",
        "tags": [
          "Notifications"
        ]
      }
    },
    "/notifications/{id}/click": {
      "put": {
        "description": "Mark a notification as clicked with detailed action tracking.\n\n## Click Tracking (クリック追跡)\nAdvanced click analytics with:\n- **Action Tracking**: Record specific actions taken by users\n- **Conversion Analytics**: Track notification-to-action conversion rates\n- **User Journey**: Understand user journey through notification interactions\n- **A/B Testing**: Support for notification A/B testing and optimization\n- **Performance Metrics**: Measure notification effectiveness and engagement\n\n## Click Actions\n- **Navigation**: Track navigation to specific pages or sections\n- **Task Completion**: Track completion of notification-related tasks\n- **External Links**: Track clicks to external URLs and systems\n- **Custom Actions**: Support for application-specific custom actions\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Notification ID to mark as clicked",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "document_click": {
                  "summary": "Click to view document",
                  "value": {
                    "clickAction": "view_document",
                    "readMethod": "web"
                  }
                },
                "task_click": {
                  "summary": "Click to complete task",
                  "value": {
                    "clickAction": "complete_task",
                    "readMethod": "mobile"
                  }
                }
              },
              "schema": {
                "description": "Use camelCase for all fields",
                "properties": {
                  "clickAction": {
                    "description": "Action taken when clicked",
                    "example": "view_document",
                    "type": "string"
                  },
                  "readMethod": {
                    "$ref": "#/components/schemas/ReadMethod"
                  }
                },
                "required": [
                  "clickAction"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/NotificationActionResponse"
                }
              }
            },
            "description": "Notification marked as clicked successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Notification not found",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Notification not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Mark notification as clicked",
        "tags": [
          "Notifications"
        ]
      }
    },
    "/notifications/{id}/read": {
      "put": {
        "description": "Mark a specific notification as read with detailed interaction tracking.\n\n## Mark as Read (既読にする)\nComprehensive read tracking with:\n- **Interaction Analytics**: Track how users interact with notifications\n- **Method Tracking**: Record the method used to read (web, push, email, mobile)\n- **Timestamp Recording**: Precise timestamp tracking for analytics\n- **Session Tracking**: Associate reads with user sessions\n- **Device Information**: Track device and browser information for analytics\n\n## Tracking Benefits\n- **User Engagement**: Understand how users engage with notifications\n- **Channel Effectiveness**: Analyze which delivery channels are most effective\n- **Performance Metrics**: Track notification performance and user behavior\n- **Optimization**: Optimize notification delivery based on user preferences\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Notification ID to mark as read",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "push_read": {
                  "summary": "Mark as read via push notification",
                  "value": {
                    "readMethod": "push"
                  }
                },
                "web_read": {
                  "summary": "Mark as read via web interface",
                  "value": {
                    "readMethod": "web"
                  }
                }
              },
              "schema": {
                "description": "Use camelCase for all fields",
                "properties": {
                  "readMethod": {
                    "$ref": "#/components/schemas/ReadMethod"
                  }
                },
                "type": "object"
              }
            }
          },
          "required": false
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/NotificationActionResponse"
                }
              }
            },
            "description": "Notification marked as read successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Notification not found",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Notification not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Mark notification as read",
        "tags": [
          "Notifications"
        ]
      }
    },
    "/officer-compensation/plan": {
      "get": {
        "description": "Read-only (BL-974). From the books (NET 604 per month), the schedule, the latest pay slip, 保険料額通知 and 社宅 charges. `status` is `in_window` (within 3 months of the fiscal-year start), `mid_year` (a change now is not 定期同額 unless a 業績悪化改定事由 applies — the 税理士 decides) or `no_compensation`. Checklist items carry primary sources; `unverified` is shown as 確認中.",
        "parameters": [
          {
            "description": "The monthly amount being considered (default 0 = stop paying)",
            "in": "query",
            "name": "newMonthlyAmount",
            "required": false,
            "schema": {
              "default": 0,
              "maximum": 100000000,
              "minimum": 0,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/OfficerCompensationPlan"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Plan"
          },
          "400": {
            "description": "Invalid amount"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "役員報酬改定 advisor — when a change stays 定期同額給与, its cost today, and its checklist",
        "tags": [
          "Officer Compensation"
        ]
      }
    },
    "/officer-compensation/plan/reminders": {
      "post": {
        "description": "Writes user-created reminders (the same rows as POST /reminders/custom; type CUSTOM, one-time) for each checklist item with a reminderTitle and a due date from today on. The title is the key: a re-post keeps existing rows and moves an open row to a changed date — it never duplicates. 201 when a row was created or moved, 200 when all already existed. The daily reminder mail does not read these rows; they show in the app.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "newMonthlyAmount": {
                    "default": 0,
                    "maximum": 100000000,
                    "minimum": 0,
                    "type": "integer"
                  }
                },
                "type": "object"
              }
            }
          },
          "required": false
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "plan": {
                          "$ref": "#/components/schemas/OfficerCompensationPlan"
                        },
                        "reminders": {
                          "items": {
                            "$ref": "#/components/schemas/OfficerCompPlanReminder"
                          },
                          "type": "array"
                        }
                      },
                      "required": [
                        "plan",
                        "reminders"
                      ],
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "All reminders already existed"
          },
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "plan": {
                          "$ref": "#/components/schemas/OfficerCompensationPlan"
                        },
                        "reminders": {
                          "items": {
                            "$ref": "#/components/schemas/OfficerCompPlanReminder"
                          },
                          "type": "array"
                        }
                      },
                      "required": [
                        "plan",
                        "reminders"
                      ],
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Reminders created or moved"
          },
          "400": {
            "description": "Invalid amount"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create the plan’s dated steps as reminders (idempotent)",
        "tags": [
          "Officer Compensation"
        ]
      }
    },
    "/openai/analyze-image": {
      "post": {
        "description": "Analyze images using OpenAI's vision-capable models to extract insights, describe content, and identify objects.\n      \n## Image Analysis Capabilities\n- **Content Description**: Detailed descriptions of image content\n- **Object Detection**: Identify and list objects in images\n- **Text Extraction**: OCR capabilities to extract text from images\n- **Scene Understanding**: Contextual analysis of scenes and situations\n\n## Input Formats\n- **Image URLs**: Direct links to publicly accessible images\n- **Base64 Encoding**: Upload images as base64-encoded data\n- **Format Support**: JPEG, PNG, GIF, and WebP formats\n- **Size Limits**: Automatic resizing for optimal processing\n\n## Analysis Parameters\n- **Detail Level**: Choose between low, high, or auto detail processing\n- **Custom Prompts**: Specify what aspects to focus on in analysis\n- **Model Selection**: Use latest vision models for best results\n- **Token Control**: Manage response length and processing costs\n\n## Use Cases\n- **Document Processing**: Extract data from invoices, receipts, forms\n- **Content Moderation**: Analyze images for inappropriate content\n- **Accessibility**: Generate alt-text descriptions for images\n- **Quality Control**: Automated inspection and quality assessment",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "base64-analysis": {
                  "summary": "Analyze base64 encoded image",
                  "value": {
                    "detail": "high",
                    "imageBase64": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQ...",
                    "maxTokens": 500,
                    "prompt": "Extract all text from this document and organize it into structured data."
                  }
                },
                "url-analysis": {
                  "summary": "Analyze image from URL",
                  "value": {
                    "detail": "high",
                    "imageUrl": "https://example.com/sample-image.jpg",
                    "maxTokens": 300,
                    "model": "gpt-4-vision-preview",
                    "prompt": "Describe what you see in this image and identify any text."
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/OpenAIImageAnalysisRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-analysis": {
                    "summary": "Successful image analysis",
                    "value": {
                      "data": {
                        "content": "This image shows a modern office environment with multiple people working at computers. The space features contemporary furniture and good lighting.",
                        "extractedData": {
                          "colors": [
                            "blue",
                            "white",
                            "gray"
                          ],
                          "objects": [
                            "computer",
                            "desk",
                            "person",
                            "chair",
                            "monitor"
                          ],
                          "text": "Welcome to TechCorp"
                        },
                        "finishReason": "stop",
                        "model": "gpt-4-vision-preview",
                        "processingTime": 2500,
                        "usage": {
                          "completionTokens": 120,
                          "promptTokens": 85,
                          "totalTokens": 205
                        }
                      },
                      "message": "Image analyzed successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/OpenAIImageAnalysisResponse"
                }
              }
            },
            "description": "Image analyzed successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "examples": {
                  "invalid-url": {
                    "summary": "Invalid image URL",
                    "value": {
                      "error": "Validation Error",
                      "message": "imageUrl must be a valid URL",
                      "statusCode": 400
                    }
                  },
                  "missing-image": {
                    "summary": "No image provided",
                    "value": {
                      "error": "Validation Error",
                      "message": "Either imageUrl or imageBase64 must be provided",
                      "statusCode": 400
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Invalid request parameters"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Rate limit exceeded"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Analyze images using OpenAI vision models",
        "tags": [
          "OpenAI"
        ]
      }
    },
    "/openai/api-key": {
      "delete": {
        "description": "Permanently remove a user's stored OpenAI API key from the system with secure cleanup.\n      \n## Key Removal Process\n- **Secure Deletion**: Complete removal from all storage systems\n- **Audit Trail**: Deletion events logged for security compliance\n- **Immediate Effect**: Key becomes unusable immediately after deletion\n- **Fallback Behavior**: System falls back to default service behavior\n\n## Security Considerations\n- **Permanent Deletion**: Keys cannot be recovered after deletion\n- **Access Revocation**: All access using the key is immediately revoked\n- **Cleanup Process**: All cached data associated with the key is cleared\n- **Audit Compliance**: Deletion events logged for regulatory compliance\n\n## Post-Deletion Behavior\n- **Service Continuity**: AI services continue with system fallback\n- **Usage Tracking**: Historical usage data is preserved for billing\n- **Re-registration**: Users can add a new API key at any time\n- **Security Notifications**: Users are notified of key removal\n\n## Privacy Protection\n- **Data Minimization**: Only necessary audit data is retained\n- **User Rights**: Supports user's right to data deletion\n- **Compliance**: Meets GDPR and other privacy regulation requirements\n- **Secure Logging**: Audit logs never contain actual key values",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-deletion": {
                    "summary": "Successful API key removal",
                    "value": {
                      "data": "API key has been permanently removed from your account",
                      "message": "API key removed successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ApiKeyDeleteResponse"
                }
              }
            },
            "description": "API key removed successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "examples": {
                  "no-key-found": {
                    "summary": "No API key to remove",
                    "value": {
                      "error": "Not Found",
                      "message": "No API key found for this user",
                      "statusCode": 404
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "No API key found to remove"
          },
          "429": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Rate limit exceeded"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Remove user OpenAI API key",
        "tags": [
          "OpenAI"
        ]
      },
      "put": {
        "description": "Store and validate a user's personal OpenAI API key for enhanced service access and personalized usage tracking.\n      \n## API Key Management\n- **Secure Storage**: API keys are encrypted before storage\n- **Validation**: Keys are validated against OpenAI API before saving\n- **User Isolation**: Each user's API key is completely isolated\n- **Audit Trail**: All API key operations are logged for security\n\n## Benefits of Personal API Keys\n- **Cost Control**: Direct billing to user's OpenAI account\n- **Higher Limits**: Access to user's OpenAI rate limits\n- **Model Access**: Use models available in user's OpenAI account\n- **Usage Tracking**: Detailed usage statistics and cost monitoring\n\n## Security Features\n- **Encryption**: Keys encrypted with user-specific encryption\n- **Access Control**: Only the key owner can view or modify\n- **Validation**: Real-time validation against OpenAI API\n- **Secure Transmission**: HTTPS-only transmission and storage\n\n## Privacy and Compliance\n- **Data Protection**: Keys never logged or exposed in responses\n- **User Control**: Users can remove keys at any time\n- **Compliance**: Meets security standards for API key handling\n- **Audit Logging**: Security events logged without exposing keys",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "api-key-update": {
                  "summary": "Update OpenAI API key",
                  "value": {
                    "apiKey": "sk-proj-1234567890abcdef..."
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/UpdateApiKeyRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-update": {
                    "summary": "Successful API key update",
                    "value": {
                      "data": "API key has been securely stored and validated",
                      "message": "API key updated successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ApiKeyUpdateResponse"
                }
              }
            },
            "description": "API key updated successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "examples": {
                  "invalid-format": {
                    "summary": "Invalid API key format",
                    "value": {
                      "error": "Validation Error",
                      "message": "API key must start with sk- and be properly formatted",
                      "statusCode": 400
                    }
                  },
                  "validation-failed": {
                    "summary": "API key validation failed",
                    "value": {
                      "error": "Validation Error",
                      "message": "API key is invalid or has insufficient permissions",
                      "statusCode": 400
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Invalid API key format or validation failed"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Rate limit exceeded"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update user OpenAI API key",
        "tags": [
          "OpenAI"
        ]
      }
    },
    "/openai/api-key/status": {
      "get": {
        "description": "Retrieve the current status of the user's stored OpenAI API key without exposing the actual key value.\n      \n## Status Information\n- **Key Presence**: Whether a key is stored for the user\n- **Validation Status**: Whether the stored key is currently valid\n- **Usage History**: When the key was last successfully used\n- **Security Status**: Any security-related information about the key\n\n## Privacy Protection\n- **No Key Exposure**: Actual API key values are never returned\n- **Status Only**: Only metadata and status information provided\n- **Security First**: Designed to prevent key leakage or exposure\n- **Audit Safe**: Safe to call for status checks and monitoring\n\n## Use Cases\n- **Frontend Integration**: Check if user needs to provide an API key\n- **Service Health**: Monitor API key validity and usage\n- **User Experience**: Provide clear status information to users\n- **Troubleshooting**: Help diagnose API key related issues\n\n## Security Features\n- **Authentication Required**: Requires valid user authentication\n- **User Isolation**: Users can only see their own key status\n- **Rate Limited**: Protected against abuse and enumeration attacks\n- **Audit Logged**: All status checks are logged for security monitoring",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "key-invalid": {
                    "summary": "API key present but invalid",
                    "value": {
                      "data": {
                        "hasApiKey": true,
                        "isValid": false,
                        "lastUsed": "2024-01-10T08:15:00.000Z"
                      },
                      "message": "API key status retrieved successfully",
                      "statusCode": 200
                    }
                  },
                  "key-present-valid": {
                    "summary": "API key present and valid",
                    "value": {
                      "data": {
                        "hasApiKey": true,
                        "isValid": true,
                        "lastUsed": "2024-01-15T10:30:00.000Z"
                      },
                      "message": "API key status retrieved successfully",
                      "statusCode": 200
                    }
                  },
                  "no-key": {
                    "summary": "No API key stored",
                    "value": {
                      "data": {
                        "hasApiKey": false
                      },
                      "message": "API key status retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ApiKeyStatusResponse"
                }
              }
            },
            "description": "API key status retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get user API key status",
        "tags": [
          "OpenAI"
        ]
      }
    },
    "/openai/generate-embeddings": {
      "post": {
        "description": "Generate vector embeddings for text using OpenAI's embedding models for semantic search and similarity analysis.\n      \n## Embedding Applications\n- **Semantic Search**: Find similar content based on meaning, not keywords\n- **Content Clustering**: Group related documents and articles\n- **Recommendation Systems**: Suggest similar products or content\n- **Duplicate Detection**: Identify duplicate or near-duplicate content\n\n## Vector Operations\n- **Similarity Calculation**: Use cosine similarity for content matching\n- **Dimensionality Options**: Choose embedding dimensions for performance\n- **Batch Processing**: Generate embeddings for multiple texts efficiently\n- **Model Selection**: Use latest embedding models for best quality\n\n## Performance Features\n- **Optimized Models**: Fast and accurate embedding generation\n- **Batch Support**: Process multiple texts in a single request\n- **Dimension Control**: Balance quality vs. storage requirements\n- **Cost Efficiency**: Optimized token usage for embedding generation\n\n## Integration Use Cases\n- **Search Enhancement**: Improve search relevance with semantic matching\n- **Content Analysis**: Analyze document similarity and relationships\n- **Data Classification**: Automatically categorize and tag content\n- **Knowledge Management**: Build intelligent knowledge bases",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "batch-texts": {
                  "summary": "Generate embeddings for multiple texts",
                  "value": {
                    "dimensions": 3072,
                    "input": [
                      "Machine learning is a subset of artificial intelligence.",
                      "Deep learning uses neural networks with multiple layers.",
                      "Natural language processing helps computers understand human language."
                    ],
                    "model": "text-embedding-3-large"
                  }
                },
                "single-text": {
                  "summary": "Generate embedding for single text",
                  "value": {
                    "dimensions": 1536,
                    "input": "The quick brown fox jumps over the lazy dog.",
                    "model": "text-embedding-3-small"
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/OpenAIEmbeddingRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-embeddings": {
                    "summary": "Successful embedding generation",
                    "value": {
                      "data": {
                        "embeddings": [
                          {
                            "embedding": [
                              0.1,
                              -0.2,
                              0.3,
                              0.4,
                              -0.1,
                              0.5
                            ],
                            "index": 0
                          }
                        ],
                        "model": "text-embedding-3-small",
                        "usage": {
                          "promptTokens": 25,
                          "totalTokens": 25
                        }
                      },
                      "message": "Embeddings generated successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/OpenAIEmbeddingResponse"
                }
              }
            },
            "description": "Embeddings generated successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "examples": {
                  "invalid-dimensions": {
                    "summary": "Invalid dimension count",
                    "value": {
                      "error": "Validation Error",
                      "message": "Dimensions must be between 1 and 3072",
                      "statusCode": 400
                    }
                  },
                  "missing-input": {
                    "summary": "No input text provided",
                    "value": {
                      "error": "Validation Error",
                      "message": "Input text is required",
                      "statusCode": 400
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Invalid request parameters"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Rate limit exceeded"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Generate text embeddings for semantic search",
        "tags": [
          "OpenAI"
        ]
      }
    },
    "/openai/generate-text": {
      "post": {
        "description": "Generate text content using OpenAI's language models with conversation context support.\n      \n## Text Generation Features\n- **Multi-turn Conversations**: Support for system, user, and assistant message roles\n- **Model Selection**: Choose from various OpenAI models (GPT-3.5, GPT-4, etc.)\n- **Parameter Control**: Fine-tune temperature, top-p, and token limits\n- **Fallback Support**: Optional fallback to system API key for reliability\n\n## Usage Tracking\n- **Token Monitoring**: Track prompt and completion token usage\n- **Cost Estimation**: Monitor API costs and usage patterns\n- **Rate Limiting**: Automatic rate limiting to prevent abuse\n- **Billing Integration**: Usage data for accurate billing calculations\n\n## Security Features\n- **Authentication Required**: JWT token authentication for all requests\n- **API Key Management**: User-specific API keys with secure encryption\n- **Input Validation**: Comprehensive validation of all request parameters\n- **Audit Logging**: Complete audit trail of AI operations\n\n## Model Parameters\n- **Temperature**: Controls creativity (0 = deterministic, 2 = very creative)\n- **Top-P**: Nucleus sampling for response diversity\n- **Max Tokens**: Limit response length to control costs\n- **Model Selection**: Choose optimal model for your use case",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "conversation-context": {
                  "summary": "Multi-turn conversation",
                  "value": {
                    "maxTokens": 500,
                    "messages": [
                      {
                        "content": "You are a helpful coding assistant.",
                        "role": "system"
                      },
                      {
                        "content": "How do I create a REST API in Node.js?",
                        "role": "user"
                      },
                      {
                        "content": "To create a REST API in Node.js, you can use Express.js...",
                        "role": "assistant"
                      },
                      {
                        "content": "Can you show me an example?",
                        "role": "user"
                      }
                    ],
                    "model": "gpt-4",
                    "temperature": 0.3
                  }
                },
                "simple-question": {
                  "summary": "Simple question answering",
                  "value": {
                    "maxTokens": 150,
                    "messages": [
                      {
                        "content": "What is artificial intelligence?",
                        "role": "user"
                      }
                    ],
                    "model": "gpt-3.5-turbo",
                    "temperature": 0.7
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/OpenAITextGenerationRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "successful-generation": {
                    "summary": "Successful text generation",
                    "value": {
                      "data": {
                        "content": "Artificial intelligence (AI) is a branch of computer science that aims to create machines capable of performing tasks that typically require human intelligence...",
                        "finishReason": "stop",
                        "model": "gpt-3.5-turbo",
                        "usage": {
                          "completionTokens": 150,
                          "promptTokens": 25,
                          "totalTokens": 175
                        }
                      },
                      "message": "Text generated successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/OpenAITextGenerationResponse"
                }
              }
            },
            "description": "Text generated successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "examples": {
                  "invalid-messages": {
                    "summary": "Invalid message format",
                    "value": {
                      "error": "Validation Error",
                      "message": "Messages array is required and must contain at least one message",
                      "statusCode": 400
                    }
                  },
                  "invalid-parameters": {
                    "summary": "Invalid model parameters",
                    "value": {
                      "error": "Validation Error",
                      "message": "Temperature must be between 0 and 2",
                      "statusCode": 400
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Invalid request parameters"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "content": {
              "application/json": {
                "examples": {
                  "rate-limit": {
                    "summary": "Rate limit exceeded",
                    "value": {
                      "error": "Rate Limit Exceeded",
                      "message": "Too many AI requests. Please try again later.",
                      "statusCode": 429
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Rate limit exceeded"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Generate text using OpenAI models",
        "tags": [
          "OpenAI"
        ]
      }
    },
    "/openai/usage": {
      "get": {
        "deprecated": true,
        "description": "Deprecated. Responds **307 Temporary Redirect** to `/api/client-usage/stats?source=langfuse` and carries over the caller's query string (start_date, end_date, group_by). Call `GET /api/client-usage/stats` directly.",
        "responses": {
          "307": {
            "description": "Temporary redirect to /api/client-usage/stats?source=langfuse (query string preserved)"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Deprecated: redirects to /client-usage/stats",
        "tags": [
          "OpenAI"
        ]
      }
    },
    "/pay-slips": {
      "get": {
        "description": "Retrieve paginated list of pay slips for the authenticated user with comprehensive filtering options.\n\n## Pay Slip Management (給与明細管理)\nComprehensive payroll management with:\n- **Japanese Payroll Standards**: Full compliance with Japanese payroll and tax standards\n- **YTD Tracking**: Year-to-date tracking for tax and social insurance compliance\n- **Employee Management**: Department-based organization and employee tracking\n- **Pay Period Flexibility**: Flexible pay period management with YYYYMMDD date format\n- **Status Workflow**: Complete pay slip lifecycle management with status tracking\n- **Document Integration**: Seamless integration with document storage system\n\n## Filtering Options\n- **Employee Name**: Filter by employee name (Japanese supported)\n- **Date Range**: Filter by pay period start and end dates\n- **Status**: Filter by pay slip status (draft, active, paid, cancelled)\n- **Pagination**: Efficient pagination with configurable page sizes\n\n## Pay Slip Information\n- **Employee Details**: Name, department, and organizational information\n- **Pay Period**: Start and end dates with payment date tracking\n- **Financial Details**: Gross salary, deductions, and net pay calculations\n- **YTD Tracking**: Comprehensive year-to-date tracking for compliance\n- **Items**: Detailed earnings and deductions breakdown\n\n## Use Cases\n- **Payroll Administration**: Manage employee payroll and pay slip generation\n- **Tax Compliance**: Track YTD amounts for tax reporting and compliance\n- **Accounting Integration**: Generate journal entries for accounting systems\n- **Employee Self-Service**: Provide employees with pay slip access\n- **Audit Trail**: Maintain complete audit trail for payroll compliance\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Page number for pagination",
            "in": "query",
            "name": "page_number",
            "required": false,
            "schema": {
              "default": 1,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "description": "Number of pay slips per page",
            "in": "query",
            "name": "page_size",
            "required": false,
            "schema": {
              "default": 20,
              "maximum": 100,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "description": "Filter by employee name (partial match supported)",
            "in": "query",
            "name": "employee_name",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "Filter by pay period start date (YYYYMMDD format)",
            "example": 20240101,
            "in": "query",
            "name": "start_date",
            "required": false,
            "schema": {
              "maximum": 99991231,
              "minimum": 19700101,
              "type": "integer"
            }
          },
          {
            "description": "Filter by pay period end date (YYYYMMDD format)",
            "example": 20240131,
            "in": "query",
            "name": "end_date",
            "required": false,
            "schema": {
              "maximum": 99991231,
              "minimum": 19700101,
              "type": "integer"
            }
          },
          {
            "description": "Filter by pay slip status",
            "in": "query",
            "name": "status",
            "required": false,
            "schema": {
              "$ref": "#/components/schemas/PaySlipStatus"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "monthly_payslips": {
                    "summary": "Monthly pay slips with various employees",
                    "value": {
                      "data": [
                        {
                          "created_at": "2024-01-15T10:30:00.000Z",
                          "created_by": "def67890-abc1-2345-6789-0123456789ab",
                          "document_id": "456e7890-f12a-34b5-c678-901234567890",
                          "employee_department": "営業部",
                          "employee_name": "田中太郎",
                          "gross_salary": 350000,
                          "id": "123e4567-e89b-12d3-a456-426614174000",
                          "items": [
                            {
                              "amount": 250000,
                              "id": "item1-123e-4567-e89b-12d3a456614174000",
                              "is_earning": true,
                              "item_name": "基本給",
                              "notes": "Monthly base salary",
                              "pay_slip_id": "123e4567-e89b-12d3-a456-426614174000",
                              "type": 1
                            },
                            {
                              "amount": 100000,
                              "id": "item2-456e-7890-f12a-34b5c678901234567890",
                              "is_earning": true,
                              "item_name": "残業代",
                              "notes": "40 hours overtime",
                              "pay_slip_id": "123e4567-e89b-12d3-a456-426614174000",
                              "type": 2
                            }
                          ],
                          "journal_entries_id": null,
                          "net_pay": 265000,
                          "pay_period_end": 20240131,
                          "pay_period_start": 20240101,
                          "payment_date": 20240225,
                          "provision_note": "Overtime pay included for January",
                          "status": 1,
                          "total_deductions": 85000,
                          "updated_at": "2024-01-15T10:30:00.000Z",
                          "ytd_gross": 1050000,
                          "ytd_income_tax": 85000,
                          "ytd_social_ins": 150000,
                          "ytd_taxable": 1000000
                        }
                      ],
                      "message": "Pay slips retrieved successfully",
                      "pagination": {
                        "currentPage": 1,
                        "hasNext": true,
                        "hasPrevious": false,
                        "pageSize": 20,
                        "totalItems": 25,
                        "totalPages": 2
                      },
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/PaySlipListResponse"
                }
              }
            },
            "description": "Pay slips retrieved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get pay slips with pagination and filtering",
        "tags": [
          "Pay Slips"
        ]
      },
      "post": {
        "description": "Create a new pay slip with comprehensive employee and payroll information.\n\n## Pay Slip Creation (給与明細作成)\nComprehensive pay slip creation with:\n- **Employee Information**: Complete employee details with department tracking\n- **Pay Period Management**: Flexible pay period definition with payment dates\n- **Financial Calculations**: Accurate gross salary, deductions, and net pay calculations\n- **YTD Tracking**: Automatic year-to-date calculations for tax compliance\n- **Item Management**: Detailed earnings and deductions with categorization\n- **Document Integration**: Optional document attachment for pay slip storage\n\n## Financial Components\n- **Gross Salary**: Total earnings before deductions\n- **Deductions**: Comprehensive deduction tracking (tax, insurance, etc.)\n- **Net Pay**: Final amount after all deductions\n- **YTD Tracking**: Year-to-date amounts for compliance and reporting\n\n## Pay Slip Items\n- **Earnings**: Base salary, overtime, bonuses, allowances\n- **Deductions**: Income tax, social insurance, health insurance, pension\n- **Categorization**: Flexible item categorization with earning/deduction flags\n- **Notes**: Additional notes for each item for clarity and documentation\n\n## Japanese Compliance\n- **Tax Standards**: Compliance with Japanese income tax standards\n- **Social Insurance**: Social insurance calculation and tracking\n- **YTD Requirements**: Year-to-date tracking for annual tax reporting\n- **Date Formats**: YYYYMMDD date format for Japanese business standards\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "monthly_payslip": {
                  "summary": "Monthly pay slip with overtime",
                  "value": {
                    "employee_department": "営業部",
                    "employee_name": "田中太郎",
                    "gross_salary": 350000,
                    "items": [
                      {
                        "amount": 250000,
                        "is_earning": true,
                        "item_name": "基本給",
                        "notes": "Monthly base salary",
                        "type": 1
                      },
                      {
                        "amount": 100000,
                        "is_earning": true,
                        "item_name": "残業代",
                        "notes": "40 hours overtime",
                        "type": 2
                      },
                      {
                        "amount": 35000,
                        "is_earning": false,
                        "item_name": "所得税",
                        "notes": "Income tax deduction",
                        "type": 10
                      },
                      {
                        "amount": 50000,
                        "is_earning": false,
                        "item_name": "社会保険料",
                        "notes": "Social insurance premium",
                        "type": 11
                      }
                    ],
                    "net_pay": 265000,
                    "pay_period_end": 20240131,
                    "pay_period_start": 20240101,
                    "payment_date": 20240225,
                    "provision_note": "Overtime pay included for January",
                    "total_deductions": 85000,
                    "ytd_gross": 1050000,
                    "ytd_income_tax": 85000,
                    "ytd_social_ins": 150000,
                    "ytd_taxable": 1000000
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/CreatePaySlipRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PaySlipResponse"
                }
              }
            },
            "description": "Pay slip created successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "409": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "DUPLICATE_PAY_SLIP",
                      "type": "string"
                    },
                    "error": {
                      "example": "Pay slip already exists for 田中太郎 for period 20240101-20240131",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Duplicate pay slip detected"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create a new pay slip",
        "tags": [
          "Pay Slips"
        ]
      }
    },
    "/pay-slips/document/{document_id}": {
      "get": {
        "description": "Retrieve a pay slip associated with a specific document.\n\n## Document Integration (文書連携)\nSeamless document integration with:\n- **Document Linking**: Direct linking between pay slips and documents\n- **File Management**: Integration with document storage system\n- **Version Control**: Handle document versions and updates\n- **Access Control**: Ensure proper access control for document-linked pay slips\n- **Metadata Sync**: Synchronize metadata between pay slips and documents\n\n## Use Cases\n- **Document Retrieval**: Find pay slip associated with uploaded document\n- **File Processing**: Process uploaded pay slip documents\n- **Data Extraction**: Extract pay slip data from document content\n- **Verification**: Verify pay slip data against source documents\n- **Audit Trail**: Maintain connection between pay slips and source documents\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Document unique identifier",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PaySlipResponse"
                }
              }
            },
            "description": "Pay slip retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "No pay slip found for the specified document",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Pay slip not found for document"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get pay slip by document ID",
        "tags": [
          "Pay Slips"
        ]
      }
    },
    "/pay-slips/{pay_slip_id}": {
      "delete": {
        "description": "Delete a pay slip and all associated data.\n\n## Pay Slip Deletion (給与明細削除)\nSafe pay slip deletion with:\n- **Cascade Deletion**: Automatic deletion of associated pay slip items\n- **Journal Cleanup**: Proper handling of associated journal entries\n- **Document Handling**: Appropriate handling of associated documents\n- **Audit Trail**: Complete audit trail of deletion actions\n- **Status Validation**: Ensure pay slip can be safely deleted\n\n## Deletion Process\n- **Validation**: Verify pay slip can be safely deleted\n- **Item Cleanup**: Remove all associated pay slip items\n- **Journal Handling**: Handle associated journal entries appropriately\n- **Document Management**: Manage associated document references\n- **Audit Logging**: Log deletion for compliance and audit\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Pay slip unique identifier",
            "in": "path",
            "name": "pay_slip_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "deletedId": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "success": {
                          "example": true,
                          "type": "boolean"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Pay slip deleted successfully",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Pay slip deleted successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Pay slip not found",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Pay slip not found"
          },
          "409": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Cannot delete pay slip with associated journal entries",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Cannot delete pay slip"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Delete pay slip",
        "tags": [
          "Pay Slips"
        ]
      },
      "get": {
        "description": "Retrieve a specific pay slip by its unique identifier with complete details.\n\n## Pay Slip Details (給与明細詳細)\nComprehensive pay slip information with:\n- **Complete Employee Information**: Full employee details and department information\n- **Financial Breakdown**: Detailed breakdown of earnings, deductions, and calculations\n- **YTD Information**: Year-to-date tracking for tax and compliance purposes\n- **Item Details**: Complete list of earnings and deductions with categorization\n- **Document Integration**: Associated document information if available\n- **Journal Integration**: Journal entry information for accounting integration\n\n## Information Included\n- **Employee Details**: Name, department, and organizational information\n- **Pay Period**: Complete pay period and payment date information\n- **Financial Summary**: Gross salary, total deductions, and net pay\n- **YTD Tracking**: All year-to-date amounts for compliance\n- **Item Breakdown**: Detailed list of all earnings and deductions\n- **Metadata**: Creation, update, and status information\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Pay slip unique identifier",
            "in": "path",
            "name": "pay_slip_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PaySlipResponse"
                }
              }
            },
            "description": "Pay slip retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Pay slip not found",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Pay slip not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get pay slip by ID",
        "tags": [
          "Pay Slips"
        ]
      },
      "put": {
        "description": "Update an existing pay slip with new information and recalculations.\n\n## Pay Slip Update (給与明細更新)\nComprehensive pay slip updates with:\n- **Partial Updates**: Update only the fields that need to be changed\n- **Automatic Recalculation**: Automatic recalculation of totals and YTD amounts\n- **Item Management**: Add, update, or remove pay slip items\n- **Status Management**: Update pay slip status through workflow\n- **Audit Trail**: Complete audit trail of all changes made\n\n## Update Features\n- **Employee Information**: Update employee details and department\n- **Financial Adjustments**: Adjust amounts and recalculate totals\n- **YTD Updates**: Update year-to-date amounts for compliance\n- **Item Modifications**: Modify earnings and deductions items\n- **Status Changes**: Update pay slip status for workflow management\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Pay slip unique identifier",
            "in": "path",
            "name": "pay_slip_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdatePaySlipRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PaySlipResponse"
                }
              }
            },
            "description": "Pay slip updated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Pay slip not found",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Pay slip not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update pay slip",
        "tags": [
          "Pay Slips"
        ]
      }
    },
    "/pay-slips/{pay_slip_id}/generate-journal": {
      "post": {
        "description": "Generate accounting journal entries from pay slip data for seamless accounting integration.\n\n## Journal Entry Generation (仕訳生成)\nAutomated accounting integration with:\n- **Automatic Journal Creation**: Generate journal entries based on pay slip data\n- **Account Mapping**: Map pay slip items to appropriate accounting accounts\n- **Double-Entry Bookkeeping**: Ensure proper double-entry accounting principles\n- **Japanese Accounting Standards**: Compliance with Japanese accounting standards\n- **Integration**: Seamless integration with accounting journal system\n- **Audit Trail**: Complete audit trail of journal generation process\n\n## Journal Entry Components\n- **Salary Expense**: Journal entries for gross salary and earnings\n- **Deduction Liabilities**: Entries for tax and insurance deductions\n- **Payroll Payable**: Entries for net pay payable to employees\n- **Tax Liabilities**: Entries for income tax and social insurance liabilities\n- **Account Codes**: Proper account code mapping for Japanese accounting\n\n## Generated Entries\n- **Debit Entries**: Salary expense and related costs\n- **Credit Entries**: Payroll payable and tax liabilities\n- **Balance Verification**: Ensure journal entries balance properly\n- **Reference Links**: Link journal entries back to source pay slip\n- **Metadata**: Include relevant metadata for audit and tracking\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Pay slip unique identifier",
            "in": "path",
            "name": "pay_slip_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "journal_generated": {
                    "summary": "Successfully generated journal entries",
                    "value": {
                      "data": {
                        "entries_count": 4,
                        "journal_entry_id": "789e0123-e45b-67c8-d901-234567890123",
                        "total_amount": 350000
                      },
                      "message": "Journal entries generated successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/JournalGenerationResponse"
                }
              }
            },
            "description": "Journal entries generated successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Pay slip not found",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Pay slip not found"
          },
          "409": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Journal entries already generated for this pay slip",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Journal entries already generated"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Generate journal entries from pay slip",
        "tags": [
          "Pay Slips"
        ]
      }
    },
    "/professional-engagements": {
      "get": {
        "description": "Newest first. `fiscalYear` returns that year plus standing (null-year) engagements — a 顧問契約 applies to every year.",
        "parameters": [
          {
            "in": "query",
            "name": "fiscalYear",
            "required": false,
            "schema": {
              "maximum": 2100,
              "minimum": 2000,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "items": {
                        "$ref": "#/components/schemas/ProfessionalEngagement"
                      },
                      "type": "array"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Engagement list"
          },
          "401": {
            "description": "Not authenticated"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List professional engagements",
        "tags": [
          "Professional Engagements"
        ]
      },
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateProfessionalEngagementRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "description": "Created"
          },
          "400": {
            "description": "Validation error / company not registered"
          },
          "401": {
            "description": "Not authenticated"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create a professional engagement record",
        "tags": [
          "Professional Engagements"
        ]
      }
    },
    "/professional-engagements/{id}": {
      "delete": {
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Deleted"
          },
          "404": {
            "description": "Not found (or not owned by the caller)"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Delete an engagement record",
        "tags": [
          "Professional Engagements"
        ]
      },
      "patch": {
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateProfessionalEngagementRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Updated"
          },
          "400": {
            "description": "Validation error"
          },
          "404": {
            "description": "Not found (or not owned by the caller)"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Partially update an engagement record",
        "tags": [
          "Professional Engagements"
        ]
      }
    },
    "/provider-models": {
      "get": {
        "description": "Fetches live model listings from OpenAI, Anthropic, and Vertex AI (Google Gemini) simultaneously.\n\n## Behavior\n- All three providers are queried in parallel for performance\n- If one provider fails (e.g. missing API key), it is returned with an `error` field and empty `models` array\n- The overall request always returns 200 — check individual provider `error` fields for failures\n\n## Provider Coverage\n- **OpenAI**: Full live model catalog via `/v1/models` (requires `OPENAI_API_KEY`)\n- **Anthropic**: Claude model catalog via Anthropic SDK (requires `CLAUDE_API_KEY`)\n- **Vertex AI**: Google Gemini model catalog via `@google/genai` SDK (requires `GEMINI_API_KEY`)\n\nRequires Bearer token authentication.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AllProviderModelsResponse"
                }
              }
            },
            "description": "All provider models fetched (individual providers may have errors)"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Fetch live models from all providers in parallel",
        "tags": [
          "Provider Models"
        ]
      }
    },
    "/provider-models/anthropic": {
      "get": {
        "description": "Fetches the current Claude model catalog directly from the Anthropic API.\n\nUses the system-level `CLAUDE_API_KEY` from environment configuration.\nReturns an error field if `CLAUDE_API_KEY` is not configured.\n\nRequires Bearer token authentication.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SingleProviderModelsResponse"
                }
              }
            },
            "description": "Anthropic models retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Fetch live Anthropic models",
        "tags": [
          "Provider Models"
        ]
      }
    },
    "/provider-models/openai": {
      "get": {
        "description": "Fetches the current model catalog directly from the OpenAI API.\n\nUses the system-level `OPENAI_API_KEY` from environment configuration.\n\nRequires Bearer token authentication.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SingleProviderModelsResponse"
                }
              }
            },
            "description": "OpenAI models retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Fetch live OpenAI models",
        "tags": [
          "Provider Models"
        ]
      }
    },
    "/provider-models/vertex": {
      "get": {
        "description": "Fetches the current model catalog from Vertex AI via the Google Gemini API (`@google/genai` SDK).\n\nUses the system-level `GEMINI_API_KEY` from environment configuration.\nReturns an error field if `GEMINI_API_KEY` is not configured.\n\nRequires Bearer token authentication.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SingleProviderModelsResponse"
                }
              }
            },
            "description": "Vertex AI models retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Fetch live Vertex AI / Google Gemini models",
        "tags": [
          "Provider Models"
        ]
      }
    },
    "/public/auditor-view/{token}": {
      "get": {
        "description": "Returns the overview payload for a non-revoked, non-expired share token. **Mutating GET:** a successful resolve increments `books_share_tokens.access_count` and sets `last_accessed_at`. The `/gate` GET logs a `gate` event and does **not** increment. If the share has a passphrase, returns 401 (SHARE_PASSWORD_REQUIRED) with zero metadata — call the unlock endpoint first and send the resulting proof as `X-Share-Proof`.",
        "parameters": [
          {
            "in": "path",
            "name": "token",
            "required": true,
            "schema": {
              "pattern": "^[0-9a-fA-F]{64}$",
              "type": "string"
            }
          },
          {
            "description": "Fiscal year filter",
            "in": "query",
            "name": "fiscal_year",
            "required": false,
            "schema": {
              "maximum": 2100,
              "minimum": 2000,
              "type": "integer"
            }
          },
          {
            "description": "HMAC proof from the /unlock endpoint (password-protected shares)",
            "in": "header",
            "name": "X-Share-Proof",
            "required": false,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                }
              }
            },
            "description": "Public overview for token holder"
          },
          "401": {
            "description": "Password-protected share — call /unlock first"
          },
          "404": {
            "description": "Invalid, expired, or revoked token"
          }
        },
        "summary": "Resolve public share token → overview (no auth)",
        "tags": [
          "Auditor View"
        ]
      }
    },
    "/public/auditor-view/{token}/ask": {
      "post": {
        "description": "Answers ONE question about the share, grounded strictly in the same overview payload the public page renders (filings, snapshots, trial balance, evidence coverage, memos). No tools, no account-wide reads — the endpoint never widens what the token grants. Tax judgment is explicitly deferred to the reviewing 税理士. Rate-limited hard (LLM cost guard on an unauthenticated route).",
        "parameters": [
          {
            "description": "64-char hex share token",
            "in": "path",
            "name": "token",
            "required": true,
            "schema": {
              "pattern": "^[0-9a-fA-F]{64}$",
              "type": "string"
            }
          },
          {
            "description": "Fiscal year filter",
            "in": "query",
            "name": "fiscal_year",
            "required": false,
            "schema": {
              "maximum": 2100,
              "minimum": 2000,
              "type": "integer"
            }
          },
          {
            "description": "HMAC unlock proof (v1.<shareId>.<exp>.<hmac>). Use when the client cannot send X-Share-Proof (evidence <img>/PDF/download URLs).",
            "in": "query",
            "name": "proof",
            "required": false,
            "schema": {
              "maxLength": 256,
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "history": {
                    "description": "Client-side thread context (last exchanges).",
                    "items": {
                      "properties": {
                        "content": {
                          "maxLength": 1200,
                          "type": "string"
                        },
                        "role": {
                          "enum": [
                            "user",
                            "assistant"
                          ],
                          "type": "string"
                        }
                      },
                      "type": "object"
                    },
                    "maxItems": 12,
                    "type": "array"
                  },
                  "question": {
                    "maxLength": 600,
                    "type": "string"
                  }
                },
                "required": [
                  "question"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "answer": {
                      "type": "string"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Answer grounded in the share data"
          },
          "404": {
            "description": "Invalid, revoked, or expired token"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "502": {
            "description": "Answer generation failed"
          }
        },
        "summary": "共有資料についての質問に答える閲覧サポートAI (share-scoped Q&A)",
        "tags": [
          "Auditor View"
        ]
      }
    },
    "/public/auditor-view/{token}/audit-pack": {
      "get": {
        "parameters": [
          {
            "in": "path",
            "name": "token",
            "required": true,
            "schema": {
              "pattern": "^[0-9a-fA-F]{64}$",
              "type": "string"
            }
          },
          {
            "description": "Fiscal year filter",
            "in": "query",
            "name": "fiscal_year",
            "required": false,
            "schema": {
              "maximum": 2100,
              "minimum": 2000,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/zip": {
                "schema": {
                  "format": "binary",
                  "type": "string"
                }
              }
            },
            "description": "ZIP download",
            "headers": {
              "Content-Disposition": {
                "description": "attachment; filename=…",
                "schema": {
                  "type": "string"
                }
              }
            }
          },
          "403": {
            "description": "Token does not allow audit pack download"
          },
          "404": {
            "description": "Invalid, expired, or revoked token"
          }
        },
        "summary": "Download audit pack ZIP via share token (if allowed)",
        "tags": [
          "Auditor View"
        ]
      }
    },
    "/public/auditor-view/{token}/cta": {
      "post": {
        "description": "GTM Phase 4 loop. The unlocked view carries one link to /docs/for-tax-accountants; the page posts here before navigating so the click is logged as a `cta_click` access event beside the `resolve` that opened the share (K = cta_click / resolve). No proof required, no share metadata returned; unknown / revoked / expired tokens stay 404. Rate-limited.",
        "parameters": [
          {
            "description": "64-char hex share token",
            "in": "path",
            "name": "token",
            "required": true,
            "schema": {
              "pattern": "^[0-9a-fA-F]{64}$",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "recorded": {
                          "example": true,
                          "type": "boolean"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Recorded"
          },
          "404": {
            "description": "Unknown, revoked or expired token"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        },
        "summary": "Record that the recipient followed the 一人社長 link (loop instrumentation)",
        "tags": [
          "Auditor View"
        ]
      }
    },
    "/public/auditor-view/{token}/evidence": {
      "get": {
        "description": "Lists evidence (証憑) file metadata for the fiscal year. Only available when the token was created with evidence viewing enabled. Rate-limited.",
        "parameters": [
          {
            "description": "64-char hex share token",
            "in": "path",
            "name": "token",
            "required": true,
            "schema": {
              "pattern": "^[0-9a-fA-F]{64}$",
              "type": "string"
            }
          },
          {
            "description": "Fiscal year filter",
            "in": "query",
            "name": "fiscal_year",
            "required": false,
            "schema": {
              "maximum": 2100,
              "minimum": 2000,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "files": {
                      "items": {
                        "properties": {
                          "amount": {
                            "nullable": true,
                            "type": "string"
                          },
                          "description": {
                            "nullable": true,
                            "type": "string"
                          },
                          "entryDate": {
                            "description": "YYYYMMDD",
                            "nullable": true,
                            "type": "integer"
                          },
                          "entryNumber": {
                            "nullable": true,
                            "type": "string"
                          },
                          "fileId": {
                            "format": "uuid",
                            "type": "string"
                          },
                          "fileName": {
                            "type": "string"
                          },
                          "journalEntries": {
                            "description": "ALL 仕訳 this file substantiates (vouching direction). Flat fields above remain the first ref for back-compat.",
                            "items": {
                              "properties": {
                                "amount": {
                                  "nullable": true,
                                  "type": "string"
                                },
                                "creditAccounts": {
                                  "items": {
                                    "type": "string"
                                  },
                                  "type": "array"
                                },
                                "debitAccounts": {
                                  "items": {
                                    "type": "string"
                                  },
                                  "type": "array"
                                },
                                "description": {
                                  "nullable": true,
                                  "type": "string"
                                },
                                "entryDate": {
                                  "description": "YYYYMMDD",
                                  "type": "integer"
                                },
                                "entryNumber": {
                                  "type": "string"
                                }
                              },
                              "type": "object"
                            },
                            "type": "array"
                          },
                          "mimeType": {
                            "nullable": true,
                            "type": "string"
                          },
                          "sha256": {
                            "nullable": true,
                            "type": "string"
                          }
                        },
                        "type": "object"
                      },
                      "type": "array"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Evidence file metadata list (no binaries)"
          },
          "403": {
            "description": "Token does not allow evidence viewing"
          },
          "404": {
            "description": "Invalid, expired, or revoked token"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        },
        "summary": "List 証憑 metadata via share token (if allow_evidence_view)",
        "tags": [
          "Auditor View"
        ]
      }
    },
    "/public/auditor-view/{token}/evidence/{file_id}": {
      "get": {
        "description": "Streams one evidence file binary through a token-scoped proxy. Only available when the token allows evidence viewing and the file belongs to the token owner. Rate-limited.",
        "parameters": [
          {
            "description": "64-char hex share token",
            "in": "path",
            "name": "token",
            "required": true,
            "schema": {
              "pattern": "^[0-9a-fA-F]{64}$",
              "type": "string"
            }
          },
          {
            "description": "Evidence file id",
            "in": "path",
            "name": "file_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Fiscal year filter",
            "in": "query",
            "name": "fiscal_year",
            "required": false,
            "schema": {
              "maximum": 2100,
              "minimum": 2000,
              "type": "integer"
            }
          },
          {
            "description": "HMAC unlock proof (v1.<shareId>.<exp>.<hmac>). Use when the client cannot send X-Share-Proof (evidence <img>/PDF/download URLs).",
            "in": "query",
            "name": "proof",
            "required": false,
            "schema": {
              "maxLength": 256,
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/octet-stream": {
                "schema": {
                  "format": "binary",
                  "type": "string"
                }
              }
            },
            "description": "Binary file stream",
            "headers": {
              "Content-Disposition": {
                "description": "inline/attachment; filename=…",
                "schema": {
                  "type": "string"
                }
              }
            }
          },
          "403": {
            "description": "Token does not allow evidence viewing"
          },
          "404": {
            "description": "Invalid token or file not found"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        },
        "summary": "Stream a single 証憑 binary via token-scoped proxy",
        "tags": [
          "Auditor View"
        ]
      }
    },
    "/public/auditor-view/{token}/filing-data/{file_id}": {
      "get": {
        "description": "Returns the raw text of one filing-workspace file — the same as-filed bytes the audit pack writes into 07_申告データ — so the share can render the filing in-page instead of only offering a ZIP. Also returns `parsedFields` (labeled 項目 rows with 帳票 form ids, parsed from the COMPLETE file) so the share renders a readable per-form view alongside the verbatim text. Gated on allow_audit_pack. Bodies over 4 MB are truncated with `truncated: true`; `sha256` always covers the COMPLETE file. Rate-limited.",
        "parameters": [
          {
            "description": "64-char hex share token",
            "in": "path",
            "name": "token",
            "required": true,
            "schema": {
              "pattern": "^[0-9a-fA-F]{64}$",
              "type": "string"
            }
          },
          {
            "description": "filing_workspace_files id (from overview.externalFilings[].id)",
            "in": "path",
            "name": "file_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Fiscal year filter",
            "in": "query",
            "name": "fiscal_year",
            "required": false,
            "schema": {
              "maximum": 2100,
              "minimum": 2000,
              "type": "integer"
            }
          },
          {
            "description": "HMAC unlock proof (v1.<shareId>.<exp>.<hmac>). Use when the client cannot send X-Share-Proof (evidence <img>/PDF/download URLs).",
            "in": "query",
            "name": "proof",
            "required": false,
            "schema": {
              "maxLength": 256,
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "file": {
                      "properties": {
                        "byteSize": {
                          "type": "integer"
                        },
                        "category": {
                          "type": "string"
                        },
                        "content": {
                          "type": "string"
                        },
                        "fileName": {
                          "type": "string"
                        },
                        "fileType": {
                          "type": "string"
                        },
                        "fiscalYear": {
                          "type": "integer"
                        },
                        "id": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "isGenerated": {
                          "type": "boolean"
                        },
                        "notes": {
                          "type": "string"
                        },
                        "parsedFields": {
                          "description": "Labeled 項目 rows parsed from the COMPLETE file (readable view). Empty when the file has no parseable value elements.",
                          "items": {
                            "properties": {
                              "fieldId": {
                                "description": "XSD element id; repeats suffixed #2, #3, …",
                                "type": "string"
                              },
                              "formId": {
                                "description": "Enclosing 帳票 form id (e.g. SHA010) — null outside any form section",
                                "nullable": true,
                                "type": "string"
                              },
                              "formLabel": {
                                "description": "帳票 display name when known (eLTAX 第六号様式 etc.)",
                                "nullable": true,
                                "type": "string"
                              },
                              "label": {
                                "description": "Server label; FE upgrades via the NTA dictionary",
                                "type": "string"
                              },
                              "value": {
                                "oneOf": [
                                  {
                                    "type": "number"
                                  },
                                  {
                                    "type": "string"
                                  }
                                ]
                              },
                              "valueType": {
                                "description": "Display type hint — keeps 月数/税率/名称 out of the yen formatter",
                                "enum": [
                                  "amount",
                                  "rate",
                                  "text"
                                ],
                                "nullable": true,
                                "type": "string"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        },
                        "parsedFieldsTruncated": {
                          "type": "boolean"
                        },
                        "sha256": {
                          "type": "string"
                        },
                        "sourceLabel": {
                          "type": "string"
                        },
                        "truncated": {
                          "type": "boolean"
                        }
                      },
                      "type": "object"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Filing data text + metadata"
          },
          "403": {
            "description": "Token does not allow audit-pack / filing-data access"
          },
          "404": {
            "description": "Invalid token or file not found"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        },
        "summary": "Read one 申告データ (XTX / eLTAX XML) as text via share token",
        "tags": [
          "Auditor View"
        ]
      }
    },
    "/public/auditor-view/{token}/filing-data/{file_id}/pdf": {
      "get": {
        "description": "Renders the SAME as-filed bytes the text reader serves into 別表 pages as PDF — 別表一 / 別表四 etc. for an e-Tax XTX, 第六号様式 etc. for an eLTAX XML — because a reviewing 税理士 reads 様式, not XML. Every figure is transcribed from the transmitted file; nothing is recomputed from current books, so an amended fiscal year still renders the 当初申告 as filed. Boxes absent from the transmission stay blank rather than printing 0, and rows whose 行名 is not in the SBC dictionary print their XSD element id. Without `form` the response is a ZIP of the cover plus one PDF per 帳票; with `form` it is that single 帳票 PDF. Gated on allow_audit_pack. Rate-limited; shares the report-generation timeout budget.",
        "parameters": [
          {
            "description": "64-char hex share token",
            "in": "path",
            "name": "token",
            "required": true,
            "schema": {
              "pattern": "^[0-9a-fA-F]{64}$",
              "type": "string"
            }
          },
          {
            "description": "filing_workspace_files id (from overview.externalFilings[].id)",
            "in": "path",
            "name": "file_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "帳票 id to render alone (e-Tax HOA420 / eLTAX R0102AA250). Omit for the whole 一式 as a ZIP.",
            "in": "query",
            "name": "form",
            "required": false,
            "schema": {
              "example": "HOA420",
              "type": "string"
            }
          },
          {
            "description": "Fiscal year filter",
            "in": "query",
            "name": "fiscal_year",
            "required": false,
            "schema": {
              "maximum": 2100,
              "minimum": 2000,
              "type": "integer"
            }
          },
          {
            "description": "HMAC unlock proof (v1.<shareId>.<exp>.<hmac>). Use when the client cannot send X-Share-Proof (evidence <img>/PDF/download URLs).",
            "in": "query",
            "name": "proof",
            "required": false,
            "schema": {
              "maxLength": 256,
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/pdf": {
                "schema": {
                  "format": "binary",
                  "type": "string"
                }
              },
              "application/zip": {
                "schema": {
                  "format": "binary",
                  "type": "string"
                }
              }
            },
            "description": "Single 帳票 PDF (with `form`) or a ZIP of the whole 別表一式"
          },
          "403": {
            "description": "Token does not allow audit-pack / filing-data access"
          },
          "404": {
            "description": "Invalid token, file not found, or 帳票 absent from the filing"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        },
        "summary": "Download the as-filed filing typeset as 別表 PDF via share token",
        "tags": [
          "Auditor View"
        ]
      }
    },
    "/public/auditor-view/{token}/gate": {
      "get": {
        "description": "The only share information a valid token resolves before unlock: owner-authored sender company name, share label, fiscal-year scope, expiry, and whether a passphrase is set. Lets the recipient confirm they opened the right link before entering the password. Never includes financial data, counterparties, file names, or corporate/invoice numbers. Unknown, revoked, and expired tokens return an indistinguishable 404. Each call is logged as a `gate` access event.",
        "parameters": [
          {
            "description": "64-char hex share token",
            "in": "path",
            "name": "token",
            "required": true,
            "schema": {
              "pattern": "^[0-9a-fA-F]{64}$",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "company_name": {
                          "nullable": true,
                          "type": "string"
                        },
                        "expires_at": {
                          "format": "date-time",
                          "nullable": true,
                          "type": "string"
                        },
                        "fiscal_year": {
                          "nullable": true,
                          "type": "integer"
                        },
                        "label": {
                          "nullable": true,
                          "type": "string"
                        },
                        "password_protected": {
                          "type": "boolean"
                        }
                      },
                      "type": "object"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Gate metadata"
          },
          "404": {
            "description": "Unknown, revoked, or expired token"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        },
        "summary": "Pre-unlock gate metadata for the password screen (no auth, no proof)",
        "tags": [
          "Auditor View"
        ]
      }
    },
    "/public/auditor-view/{token}/memos": {
      "get": {
        "description": "Chronological audit memos visible to any valid, non-revoked token holder. Rate-limited.",
        "parameters": [
          {
            "description": "64-char hex share token",
            "in": "path",
            "name": "token",
            "required": true,
            "schema": {
              "pattern": "^[0-9a-fA-F]{64}$",
              "type": "string"
            }
          },
          {
            "description": "Fiscal year filter",
            "in": "query",
            "name": "fiscal_year",
            "required": false,
            "schema": {
              "maximum": 2100,
              "minimum": 2000,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "memos": {
                      "items": {
                        "type": "object"
                      },
                      "type": "array"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Audit memo list for the token holder"
          },
          "404": {
            "description": "Invalid, expired, or revoked token"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        },
        "summary": "監査メモ (修正の経緯) via share token (no auth)",
        "tags": [
          "Auditor View"
        ]
      }
    },
    "/public/auditor-view/{token}/report-data": {
      "get": {
        "description": "Structured rows for the share page's on-page readers — built by the SAME row builders as the audit-pack xlsx artifacts (02/03/10/11/12), so the page and the ZIP cannot disagree line-by-line. `type=general-ledger` without `account_code` returns the account list; with `account_code` it returns that account's running-balance transactions (capped at 2,000 rows, truncation reported). `type=fixed-assets` includes the per-asset 償却スケジュール. Gated on allow_audit_pack. Rate-limited; shares the report-generation timeout budget.",
        "parameters": [
          {
            "description": "64-char hex share token",
            "in": "path",
            "name": "token",
            "required": true,
            "schema": {
              "pattern": "^[0-9a-fA-F]{64}$",
              "type": "string"
            }
          },
          {
            "description": "Which readable pack artifact to return",
            "in": "query",
            "name": "type",
            "required": true,
            "schema": {
              "enum": [
                "profit-loss",
                "balance-sheet",
                "general-ledger",
                "fixed-assets"
              ],
              "type": "string"
            }
          },
          {
            "description": "総勘定元帳 drill-down: one account's transactions instead of the account list",
            "in": "query",
            "name": "account_code",
            "required": false,
            "schema": {
              "maxLength": 20,
              "type": "string"
            }
          },
          {
            "description": "Fiscal year filter",
            "in": "query",
            "name": "fiscal_year",
            "required": false,
            "schema": {
              "maximum": 2100,
              "minimum": 2000,
              "type": "integer"
            }
          },
          {
            "description": "HMAC unlock proof (v1.<shareId>.<exp>.<hmac>). Use when the client cannot send X-Share-Proof (evidence <img>/PDF/download URLs).",
            "in": "query",
            "name": "proof",
            "required": false,
            "schema": {
              "maxLength": 256,
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "account": {
                      "description": "general-ledger with account_code: the requested account",
                      "properties": {
                        "accountCode": {
                          "type": "string"
                        },
                        "accountName": {
                          "type": "string"
                        },
                        "closingBalance": {
                          "type": "number"
                        },
                        "openingBalance": {
                          "type": "number"
                        },
                        "transactionCount": {
                          "type": "integer"
                        }
                      },
                      "type": "object"
                    },
                    "accounts": {
                      "description": "general-ledger without account_code: accounts with balance or movement",
                      "items": {
                        "properties": {
                          "accountCode": {
                            "type": "string"
                          },
                          "accountName": {
                            "type": "string"
                          },
                          "category": {
                            "type": "string"
                          },
                          "closingBalance": {
                            "type": "number"
                          },
                          "openingBalance": {
                            "type": "number"
                          },
                          "transactionCount": {
                            "type": "integer"
                          }
                        },
                        "type": "object"
                      },
                      "type": "array"
                    },
                    "assets": {
                      "description": "fixed-assets: register rows with per-asset 償却スケジュール",
                      "items": {
                        "properties": {
                          "accumulatedDepreciation": {
                            "nullable": true,
                            "type": "number"
                          },
                          "acquisitionCost": {
                            "type": "number"
                          },
                          "acquisitionDate": {
                            "type": "string"
                          },
                          "classificationLabel": {
                            "type": "string"
                          },
                          "closingBookValue": {
                            "nullable": true,
                            "type": "number"
                          },
                          "depreciationMethodLabel": {
                            "type": "string"
                          },
                          "inServiceDate": {
                            "nullable": true,
                            "type": "string"
                          },
                          "lifecycleStatusLabel": {
                            "type": "string"
                          },
                          "location": {
                            "nullable": true,
                            "type": "string"
                          },
                          "name": {
                            "type": "string"
                          },
                          "openingBookValue": {
                            "type": "number"
                          },
                          "remarks": {
                            "nullable": true,
                            "type": "string"
                          },
                          "schedule": {
                            "items": {
                              "properties": {
                                "accumulatedDepreciation": {
                                  "type": "number"
                                },
                                "bookedDepreciation": {
                                  "type": "number"
                                },
                                "closingBookValue": {
                                  "type": "number"
                                },
                                "depreciationLimit": {
                                  "type": "number"
                                },
                                "excessDisallowed": {
                                  "type": "number"
                                },
                                "fiscalYear": {
                                  "type": "integer"
                                },
                                "monthsInService": {
                                  "type": "integer"
                                },
                                "openingBookValue": {
                                  "type": "number"
                                },
                                "period": {
                                  "type": "string"
                                },
                                "status": {
                                  "type": "string"
                                }
                              },
                              "type": "object"
                            },
                            "type": "array"
                          },
                          "usefulLife": {
                            "type": "integer"
                          }
                        },
                        "type": "object"
                      },
                      "type": "array"
                    },
                    "fiscalYear": {
                      "type": "integer"
                    },
                    "period": {
                      "properties": {
                        "endDate": {
                          "description": "YYYYMMDD",
                          "type": "integer"
                        },
                        "startDate": {
                          "description": "YYYYMMDD",
                          "type": "integer"
                        }
                      },
                      "type": "object"
                    },
                    "rows": {
                      "description": "profit-loss / balance-sheet: 会社計算規則 statement lines",
                      "items": {
                        "properties": {
                          "amount": {
                            "oneOf": [
                              {
                                "type": "number"
                              },
                              {
                                "type": "string"
                              }
                            ]
                          },
                          "item": {
                            "type": "string"
                          },
                          "kind": {
                            "enum": [
                              "section",
                              "item",
                              "subtotal",
                              "keyline"
                            ],
                            "type": "string"
                          },
                          "priorAmount": {
                            "oneOf": [
                              {
                                "type": "number"
                              },
                              {
                                "type": "string"
                              }
                            ]
                          }
                        },
                        "type": "object"
                      },
                      "type": "array"
                    },
                    "totals": {
                      "description": "fixed-assets: register totals",
                      "properties": {
                        "accumulatedDepreciation": {
                          "type": "number"
                        },
                        "acquisitionCost": {
                          "type": "number"
                        },
                        "closingBookValue": {
                          "type": "number"
                        }
                      },
                      "type": "object"
                    },
                    "transactions": {
                      "description": "general-ledger with account_code: running-balance rows",
                      "items": {
                        "properties": {
                          "balance": {
                            "type": "number"
                          },
                          "counterAccount": {
                            "type": "string"
                          },
                          "creditAmount": {
                            "type": "number"
                          },
                          "date": {
                            "description": "YYYY/MM/DD",
                            "type": "string"
                          },
                          "debitAmount": {
                            "type": "number"
                          },
                          "description": {
                            "type": "string"
                          }
                        },
                        "type": "object"
                      },
                      "type": "array"
                    },
                    "transactionsTruncated": {
                      "type": "boolean"
                    },
                    "type": {
                      "enum": [
                        "profit-loss",
                        "balance-sheet",
                        "general-ledger",
                        "fixed-assets"
                      ],
                      "type": "string"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Report rows (shape depends on `type`)"
          },
          "400": {
            "description": "Unknown report type"
          },
          "403": {
            "description": "Token does not allow audit-pack / report-data access"
          },
          "404": {
            "description": "Invalid token or account not found"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        },
        "summary": "Read 決算書 / 総勘定元帳 / 固定資産台帳 rows as JSON via share token",
        "tags": [
          "Auditor View"
        ]
      }
    },
    "/public/auditor-view/{token}/unlock": {
      "post": {
        "description": "Validates the password against the bcrypt hash stored for this share. On success, returns a short-lived HMAC proof (12h) that the viewer must include on subsequent requests as `X-Share-Proof` header (or `?proof=` for URL-only fetches). Wrong password and unknown tokens are logged and return 401 with no share metadata. Rate-limited (10 attempts / 15 min / IP in production).",
        "parameters": [
          {
            "description": "64-char hex share token",
            "in": "path",
            "name": "token",
            "required": true,
            "schema": {
              "pattern": "^[0-9a-fA-F]{64}$",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UnlockBooksShareRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/UnlockBooksShareResponse"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Unlock successful — proof valid for 12 hours"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetails"
                }
              }
            },
            "description": "Validation error (missing/invalid body or malformed token); RFC 9457 body"
          },
          "401": {
            "description": "Wrong password or unknown token (no metadata returned)"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          }
        },
        "summary": "Exchange viewer passphrase for a signed proof (password-protected links)",
        "tags": [
          "Auditor View"
        ]
      }
    },
    "/public/demo/classify-journal": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ClassifyJournalRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Classification returned"
          },
          "429": {
            "description": "Rate limited"
          }
        },
        "summary": "Classify a bank line into a draft journal entry",
        "tags": [
          "Public Demo"
        ]
      }
    },
    "/public/demo/estimate-tax": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/EstimateTaxRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Tax estimate returned"
          },
          "429": {
            "description": "Rate limited"
          }
        },
        "summary": "Estimate tax burden from revenue and expenses",
        "tags": [
          "Public Demo"
        ]
      }
    },
    "/public/demo/parse-receipt": {
      "post": {
        "requestBody": {
          "content": {
            "multipart/form-data": {
              "schema": {
                "properties": {
                  "file": {
                    "format": "binary",
                    "type": "string"
                  },
                  "filename": {
                    "type": "string"
                  }
                },
                "type": "object"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Receipt fields returned"
          },
          "429": {
            "description": "Rate limited"
          }
        },
        "summary": "Parse a receipt image or sample filename",
        "tags": [
          "Public Demo"
        ]
      }
    },
    "/public/demo/provision": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ProvisionPublicDemoRequest"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Demo workspace token returned"
          },
          "429": {
            "description": "Rate limited"
          }
        },
        "summary": "Start a one-click seeded demo workspace",
        "tags": [
          "Public Demo"
        ]
      }
    },
    "/public/demo/stats": {
      "get": {
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                }
              }
            },
            "description": "Counters returned"
          }
        },
        "summary": "Get public demo counters",
        "tags": [
          "Public Demo"
        ]
      }
    },
    "/public/document-shares/{token}": {
      "get": {
        "description": "Returns the sanitized document for a non-revoked, non-expired, shareable token. **Mutating GET:** a successful resolve increments `document_public_shares.access_count` and sets `last_accessed_at`. Unknown / revoked / expired / voided / non-shareable type → 404 or 410.",
        "parameters": [
          {
            "in": "path",
            "name": "token",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                }
              }
            },
            "description": "Document payload (and access_count incremented)"
          },
          "404": {
            "description": "Unknown or expired token"
          },
          "410": {
            "description": "Revoked, voided, or type no longer shareable"
          },
          "429": {
            "description": "Rate limited"
          }
        },
        "summary": "Resolve public document share token",
        "tags": [
          "Public Document Shares"
        ]
      }
    },
    "/public/events": {
      "post": {
        "description": "Fire-and-forget beacon for the marketing and onboarding funnel. Send once per page-hide or every 5 s. A bearer token or access cookie, when present, attaches the user id server-side; a client-supplied user id is never trusted.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ProductEventBatch"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "accepted": {
                          "example": 2,
                          "type": "integer"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Accepted — { success: true, data: { accepted: <count> } }"
          },
          "400": {
            "description": "Validation error"
          },
          "429": {
            "description": "Rate limited"
          }
        },
        "summary": "Record a batch of client-side product events",
        "tags": [
          "Product Events"
        ]
      }
    },
    "/public/lifecycle/unsubscribe": {
      "get": {
        "description": "The link in every lifecycle mail. Sets notification_preferences.lifecycle_email=false for the user the signed token names. Renders a small HTML confirmation; deadline reminders and security mail are unaffected.",
        "parameters": [
          {
            "description": "Signed unsubscribe token minted by the API for one user",
            "in": "query",
            "name": "t",
            "required": true,
            "schema": {
              "example": "v1.11111111-2222-4333-8444-555555555555.<hmac>",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "text/html": {
                "schema": {
                  "type": "string"
                }
              }
            },
            "description": "Stopped (HTML page)"
          },
          "400": {
            "content": {
              "text/html": {
                "schema": {
                  "type": "string"
                }
              }
            },
            "description": "Invalid or malformed token (HTML page)"
          },
          "429": {
            "description": "Rate limited"
          }
        },
        "summary": "Stop the lifecycle (onboarding) mail series for one user",
        "tags": [
          "Public Lifecycle"
        ]
      },
      "post": {
        "description": "The List-Unsubscribe URL of every lifecycle mail, with List-Unsubscribe-Post: List-Unsubscribe=One-Click. Mail providers POST here with no cookies; the signed token in the query is the whole authorisation. Body is ignored (form-encoded or multipart). Plain 200 on success, empty 400 on a bad token, never a redirect.",
        "parameters": [
          {
            "description": "Signed unsubscribe token minted by the API for one user",
            "in": "query",
            "name": "t",
            "required": true,
            "schema": {
              "example": "v1.11111111-2222-4333-8444-555555555555.<hmac>",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/x-www-form-urlencoded": {
              "schema": {
                "properties": {
                  "List-Unsubscribe": {
                    "example": "One-Click",
                    "type": "string"
                  }
                },
                "type": "object"
              }
            }
          },
          "required": false
        },
        "responses": {
          "200": {
            "description": "Stopped (empty body)"
          },
          "400": {
            "description": "Invalid or malformed token (empty body)"
          },
          "429": {
            "description": "Rate limited"
          }
        },
        "summary": "RFC 8058 one-click unsubscribe (sent by the mail provider)",
        "tags": [
          "Public Lifecycle"
        ]
      }
    },
    "/queue/jobs": {
      "get": {
        "description": "Retrieve a paginated list of jobs with optional filtering by status and type.\n\n## Query Parameters\n- **status**: Filter jobs by current status\n- **type**: Filter jobs by job type\n- **limit**: Number of jobs per page (default: 50, max: 100)\n- **offset**: Number of jobs to skip for pagination (default: 0)\n\n## Job Status Values\n- **pending**: Job is waiting to be processed\n- **processing**: Job is currently being processed\n- **completed**: Job finished successfully\n- **failed**: Job failed during processing\n- **retrying**: Job is scheduled for retry after failure\n- **cancelled**: Job was cancelled by user\n\n## Pagination\nResults are paginated with metadata including:\n- Total count of matching jobs\n- Current limit and offset\n- Boolean indicating if more results exist\n\n## Security\nOnly returns jobs belonging to the authenticated user.\n\n## Use Cases\n- Job monitoring dashboards\n- Processing queue management\n- Historical job analysis\n- Status-based job filtering\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Filter jobs by status",
            "in": "query",
            "name": "status",
            "required": false,
            "schema": {
              "enum": [
                "pending",
                "processing",
                "completed",
                "failed",
                "retrying",
                "cancelled"
              ],
              "type": "string"
            }
          },
          {
            "description": "Filter jobs by type",
            "example": "document_processing",
            "in": "query",
            "name": "type",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "Number of jobs per page",
            "in": "query",
            "name": "limit",
            "required": false,
            "schema": {
              "default": 50,
              "maximum": 100,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "description": "Number of jobs to skip",
            "in": "query",
            "name": "offset",
            "required": false,
            "schema": {
              "default": 0,
              "minimum": 0,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/JobsListResponse"
                }
              }
            },
            "description": "Jobs retrieved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List jobs with filtering and pagination",
        "tags": [
          "Queue Management"
        ]
      }
    },
    "/queue/jobs/type/{type}": {
      "get": {
        "description": "Retrieve all jobs of a specific type for the authenticated user.\n\n## Path Parameters\n- **type**: Job type identifier\n\n## Common Job Types\n- **document_processing**: Document analysis and text extraction\n- **file_upload**: File upload and validation processing\n- **image_processing**: Image analysis and manipulation\n- **data_analysis**: Data processing and analytics\n- **notification**: Notification delivery jobs\n- **cleanup**: System cleanup and maintenance jobs\n\n## Response Data\nReturns array of jobs matching the specified type, including:\n- All job statuses (pending, processing, completed, failed, etc.)\n- Complete job details and metadata\n- Processing history and timestamps\n\n## Security\nOnly returns jobs belonging to the authenticated user.\n\n## Use Cases\n- Type-specific job monitoring\n- Workflow analysis\n- Performance tracking by job type\n- Resource usage analysis\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Job type identifier",
            "example": "document_processing",
            "in": "path",
            "name": "type",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "items": {
                        "$ref": "#/components/schemas/QueueJob"
                      },
                      "type": "array"
                    },
                    "message": {
                      "example": "Jobs retrieved successfully",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "required": [
                    "statusCode",
                    "message",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Jobs retrieved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get jobs by type",
        "tags": [
          "Queue Management"
        ]
      }
    },
    "/queue/jobs/{id}": {
      "get": {
        "description": "Retrieve complete details for a specific job by its unique identifier.\n\n## Path Parameters\n- **id**: Unique job identifier\n\n## Response Data\nReturns complete job information including:\n- Job identification and type\n- Processing status and timestamps\n- Attempt count and configuration\n- Error information (if failed)\n- Metadata and result data\n\n## Security\nOnly allows access to jobs belonging to the authenticated user.\n\n## Use Cases\n- Job detail inspection\n- Debugging failed jobs\n- Monitoring job progress\n- Retrieving job configuration\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Unique job identifier",
            "example": "job_1640995200000_abc123def",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/JobResponse"
                }
              }
            },
            "description": "Job details retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "ACCESS_DENIED",
                      "type": "string"
                    },
                    "error": {
                      "example": "You are not authorized to access this job",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Access denied - job belongs to different user"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get job details by ID",
        "tags": [
          "Queue Management"
        ]
      }
    },
    "/queue/jobs/{id}/cancel": {
      "delete": {
        "description": "Cancel a job that is pending, processing, or retrying.\n\n## Path Parameters\n- **id**: Unique job identifier\n\n## Cancellation Behavior\n- **Pending jobs**: Cancelled immediately\n- **Processing jobs**: Marked for cancellation, stops at next checkpoint\n- **Retrying jobs**: Cancelled immediately\n- **Completed/Failed/Cancelled jobs**: Cannot be cancelled (returns error)\n\n## State Changes\nSuccessful cancellation changes job status to 'cancelled' and:\n- Sets error message to 'Job cancelled by user'\n- Records cancellation timestamp\n- Triggers cleanup of associated resources\n\n## Security\nOnly allows cancellation of jobs belonging to the authenticated user.\n\n## Use Cases\n- Stopping long-running processes\n- Cancelling incorrect job submissions\n- Resource management and cleanup\n- User-initiated job termination\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Unique job identifier",
            "example": "job_1640995200000_abc123def",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/JobCancellationResponse"
                }
              }
            },
            "description": "Job cancelled successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "ACCESS_DENIED",
                      "type": "string"
                    },
                    "error": {
                      "example": "Access denied",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Access denied - job belongs to different user"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "INVALID_STATE",
                      "type": "string"
                    },
                    "error": {
                      "example": "Job cannot be cancelled in current state",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Job cannot be cancelled (already completed/failed/cancelled)"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Cancel a job",
        "tags": [
          "Queue Management"
        ]
      }
    },
    "/queue/jobs/{id}/result": {
      "get": {
        "description": "Retrieve the result data from a completed job.\n\n## Path Parameters\n- **id**: Unique job identifier\n\n## Result Availability\n- Only available for jobs with status 'completed'\n- Returns HTTP 409 if job is not yet completed\n- Result structure varies by job type\n\n## Common Result Types\n- **Document Processing**: Extracted text, metadata, page count\n- **File Upload**: File URLs, validation results\n- **Data Analysis**: Processed data, statistics, insights\n- **Image Processing**: Processed images, analysis results\n\n## Security\nOnly allows access to jobs belonging to the authenticated user.\n\n## Use Cases\n- Retrieving processed data\n- Downloading generated files\n- Accessing analysis results\n- Integration with downstream processes\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Unique job identifier",
            "example": "job_1640995200000_abc123def",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/JobResultResponse"
                }
              }
            },
            "description": "Job result retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "ACCESS_DENIED",
                      "type": "string"
                    },
                    "error": {
                      "example": "Access denied",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Access denied - job belongs to different user"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "JOB_NOT_COMPLETED",
                      "type": "string"
                    },
                    "error": {
                      "example": "Job not completed yet",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Job not completed yet"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get job result",
        "tags": [
          "Queue Management"
        ]
      }
    },
    "/queue/jobs/{id}/status": {
      "get": {
        "description": "Retrieve the current status of a specific job with completion details.\n\n## Path Parameters\n- **id**: Unique job identifier\n\n## Response Data\nReturns job status information including:\n- Current processing status\n- Completion timestamp (if finished)\n- Result preview (if completed)\n\n## Status Tracking\nProvides real-time status updates for:\n- Processing progress monitoring\n- Completion notifications\n- Failure detection and reporting\n\n## Security\nOnly allows access to jobs belonging to the authenticated user.\n\n## Use Cases\n- Real-time job monitoring\n- Status polling for UI updates\n- Completion detection\n- Progress tracking\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Unique job identifier",
            "example": "job_1640995200000_abc123def",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/JobStatusResponse"
                }
              }
            },
            "description": "Job status retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "ACCESS_DENIED",
                      "type": "string"
                    },
                    "error": {
                      "example": "Access denied",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Access denied - job belongs to different user"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get job status",
        "tags": [
          "Queue Management"
        ]
      }
    },
    "/reconciliation/auto-match": {
      "post": {
        "description": "Execute automatic reconciliation matching using rules and AI algorithms.\n\n## Auto-Matching (自動照合)\nIntelligent automation with:\n- **Rule-Based Matching**: Apply user-defined rules for automatic matching\n- **AI Algorithms**: Machine learning algorithms for fuzzy matching\n- **Pattern Recognition**: Use detected patterns for improved matching\n- **Confidence Thresholds**: Configurable confidence thresholds for automation\n- **Manual Review**: Flag low-confidence matches for manual review\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ReconciliationActionResponse"
                }
              }
            },
            "description": "Auto-matching completed successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Run automatic matching process",
        "tags": [
          "Bank Reconciliation"
        ]
      }
    },
    "/reconciliation/booking-suggestions": {
      "get": {
        "description": "Without `bank_transaction_id`: one suggestion per 未仕訳 bank row under the same filters as `GET /bank-statements/unjournalized-ids` (newest first, at most `limit`). With it: that one row, booked or not; a booked row’s own entry is left out of its history. Read-only — nothing is posted; the owner posts through `/reconciliation/create-expense` (preview first) or `/reconciliation/create-compound-journal`. Payroll and payout-document precedents are never proposed (`document_driven`).",
        "operationId": "getBookingSuggestions",
        "parameters": [
          {
            "in": "query",
            "name": "bank_transaction_id",
            "required": false,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "YYYYMMDD",
            "in": "query",
            "name": "start_date",
            "required": false,
            "schema": {
              "type": "integer"
            }
          },
          {
            "description": "YYYYMMDD",
            "in": "query",
            "name": "end_date",
            "required": false,
            "schema": {
              "type": "integer"
            }
          },
          {
            "description": "A bank account id, or 'unassigned'",
            "in": "query",
            "name": "bank_account_id",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "source",
            "required": false,
            "schema": {
              "enum": [
                "manual",
                "csv_import",
                "api_gmo_aozora",
                "paste"
              ],
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "limit",
            "required": false,
            "schema": {
              "default": 200,
              "maximum": 500,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BookingSuggestionsResponse"
                }
              }
            },
            "description": "Suggestions"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "「前回と同じ」 booking suggestions from the tenant’s own history",
        "tags": [
          "Bank Reconciliation"
        ]
      }
    },
    "/reconciliation/bulk-match": {
      "post": {
        "description": "Perform bulk matching of multiple bank transactions with journal entries for efficient reconciliation.\n\n## Bulk Matching (一括照合) - v4.54 Parallel\n\nEfficient bulk processing with **~3x faster** parallel execution:\n- **Parallel Processing (v4.54)**: Concurrent confirmations with sliding window (3 parallel)\n- **Batch Processing**: Process multiple matches efficiently\n- **Validation**: Comprehensive validation of all matches before processing\n- **Per-Item Retries**: Failed matches retry individually without blocking others\n- **Performance**: Optimized for large-scale reconciliation operations\n- **Error Reporting**: Detailed error reporting for failed matches\n\n## Performance (v4.54)\n\n| Matches | Before (Sequential) | After (Parallel) | Speedup |\n|---------|---------------------|------------------|---------|\n| 5       | ~7.5s               | ~2.5s            | ~3x     |\n| 10      | ~15s                | ~5s              | ~3x     |\n| 20      | ~30s                | ~10s             | ~3x     |\n\n## Batch Constraints\n- **Concurrency**: 3 parallel matches (controlled to avoid database contention)\n- **Size Limits**: Recommended max 50 matches per request\n- **Validation**: Pre-validation of all matches before processing\n- **Error Isolation**: Individual failures don't block other matches\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "matches": {
                    "items": {
                      "properties": {
                        "bank_amount_applied": {
                          "format": "decimal",
                          "type": "number"
                        },
                        "bank_transaction_id": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "journal_amount_applied": {
                          "format": "decimal",
                          "type": "number"
                        },
                        "journal_entry_id": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "match_type": {
                          "$ref": "#/components/schemas/MatchType"
                        }
                      },
                      "type": "object"
                    },
                    "maxItems": 100,
                    "minItems": 1,
                    "type": "array"
                  }
                },
                "required": [
                  "matches"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ReconciliationActionResponse"
                }
              }
            },
            "description": "Bulk match completed successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Bulk match multiple transactions",
        "tags": [
          "Bank Reconciliation"
        ]
      }
    },
    "/reconciliation/create-compound-journal": {
      "post": {
        "description": "Create a compound journal entry with multiple debit/credit lines from a bank transaction.\n\n## 複合仕訳 (Compound Journal Entry) - v4.35\n\nThis endpoint supports multi-line journal entries required for complex transactions like:\n- **Interest Income (受取利息)**: 3-line entry with withholding tax\n- **Reimbursements with multiple categories**: Split expense entries\n- **Foreign currency transactions**: Entries with FX gain/loss\n\n## Japanese Interest Income (銀行利息) Example\n\nFor corporations (法人), bank interest income requires a **3-line journal entry** to properly record:\n1. Net amount received (手取り額)\n2. Withholding tax paid (源泉徴収税 - 15.315%)\n3. Gross interest income (税引前受取利息)\n\n### Tax Rate (法人): 15.315%\n- 所得税 (Income Tax): 15%\n- 復興特別所得税 (Reconstruction Tax): 0.315%\n\n### Example: Net Interest ¥851\n\n| Side | Account Code | Account Name | Amount |\n|------|-------------|--------------|--------|\n| 借方 (Debit) | 102 | 普通預金 | ¥851 |\n| 借方 (Debit) | 137 | 仮払法人税等 | ¥154 |\n| 貸方 (Credit) | 403 | 受取利息 | ¥1,005 |\n\n### Calculation\n- Gross = Net ÷ (1 - 0.15315) = ¥851 ÷ 0.84685 = ¥1,005\n- Tax = Gross - Net = ¥1,005 - ¥851 = ¥154\n\n## Validation Rules (会計ルール)\n\n1. **Balance Check**: 借方合計 = 貸方合計 (must balance within ¥1)\n2. **Minimum Lines**: At least 2 lines required (複式簿記)\n3. **Amount Validation**: All amounts must be positive\n4. **Account Codes**: Must be 3-4 digit numeric codes\n5. **Single Side Per Line**: Each line is either debit OR credit, not both\n\n## Why This Matters (なぜ重要か)\n\nUsing the correct 3-line entry for interest income allows:\n- **所得税額控除**: Withholding tax credit on corporate tax return\n- **正確な収益認識**: Accurate revenue recognition (gross basis / 総額主義)\n- **税務調査対応**: Proper audit trail for tax authorities\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "bank_transaction_id": {
                    "description": "UUID of the bank transaction to link",
                    "example": "1a917c7d-c21a-4a10-ba8f-b8ac8adc38c0",
                    "format": "uuid",
                    "type": "string"
                  },
                  "category": {
                    "description": "Category code for the transaction",
                    "example": 4,
                    "type": "number"
                  },
                  "description": {
                    "description": "Overall journal entry description",
                    "example": "銀行利息（源泉徴収税込）",
                    "type": "string"
                  },
                  "entries": {
                    "description": "Journal entry lines (minimum 2)",
                    "example": [
                      {
                        "account_code": "102",
                        "account_name": "普通預金",
                        "credit_amount": 0,
                        "debit_amount": 851
                      },
                      {
                        "account_code": "137",
                        "account_name": "仮払法人税等",
                        "credit_amount": 0,
                        "debit_amount": 154
                      },
                      {
                        "account_code": "403",
                        "account_name": "受取利息",
                        "credit_amount": 1005,
                        "debit_amount": 0
                      }
                    ],
                    "items": {
                      "properties": {
                        "account_code": {
                          "description": "Account code (3-4 digits)",
                          "example": "102",
                          "type": "string"
                        },
                        "account_name": {
                          "description": "Account name (optional, for display)",
                          "example": "普通預金",
                          "type": "string"
                        },
                        "credit_amount": {
                          "description": "Credit amount (use 0 for debit-only line)",
                          "example": 0,
                          "type": "number"
                        },
                        "debit_amount": {
                          "description": "Debit amount (use 0 for credit-only line)",
                          "example": 851,
                          "type": "number"
                        },
                        "description": {
                          "description": "Line-specific description",
                          "example": "普通預金 利息",
                          "type": "string"
                        },
                        "tax_category": {
                          "description": "Per-line 消費税区分, persisted as journal_entry_lines.tax_code",
                          "example": "課税仕入10%",
                          "type": "string"
                        }
                      },
                      "required": [
                        "account_code",
                        "debit_amount",
                        "credit_amount"
                      ],
                      "type": "object"
                    },
                    "minItems": 2,
                    "type": "array"
                  },
                  "entry_type": {
                    "description": "Type of entry (used for validation and source_type)",
                    "enum": [
                      "interest_income",
                      "expense",
                      "revenue",
                      "other"
                    ],
                    "example": "interest_income",
                    "type": "string"
                  },
                  "is_ai_assisted": {
                    "description": "True when the AI bulk-journalize assistant generated the entry",
                    "type": "boolean"
                  }
                },
                "required": [
                  "bank_transaction_id",
                  "entries"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "interest-income": {
                    "summary": "Interest Income (受取利息) - 3 lines",
                    "value": {
                      "data": {
                        "journal_entry_id": "abc12345-6789-defg-hijk-lmnopqrstuvw",
                        "line_count": 3,
                        "status": "matched",
                        "success": true,
                        "total_credit": 1005,
                        "total_debit": 1005
                      },
                      "message": "Compound journal entry created from bank transaction",
                      "success": true
                    }
                  }
                },
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "journal_entry_id": {
                          "example": "abc12345-6789-defg-hijk-lmnopqrstuvw",
                          "format": "uuid",
                          "type": "string"
                        },
                        "line_count": {
                          "example": 3,
                          "type": "number"
                        },
                        "status": {
                          "example": "matched",
                          "type": "string"
                        },
                        "success": {
                          "example": true,
                          "type": "boolean"
                        },
                        "total_credit": {
                          "example": 1005,
                          "type": "number"
                        },
                        "total_debit": {
                          "example": 1005,
                          "type": "number"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Compound journal entry created from bank transaction",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Compound journal entry created successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "examples": {
                  "both-sides": {
                    "summary": "Both debit and credit on same line",
                    "value": {
                      "error": "勘定科目 102 に借方と貸方の両方が設定されています。各行は借方または貸方のいずれか一方のみです。",
                      "success": false
                    }
                  },
                  "invalid-amount": {
                    "summary": "Invalid amount",
                    "value": {
                      "error": "勘定科目 102 の金額が無効です。金額は正の数である必要があります。",
                      "success": false
                    }
                  },
                  "unbalanced": {
                    "summary": "Unbalanced entry",
                    "value": {
                      "error": "仕訳の貸借が一致しません：借方合計 ¥1,000 ≠ 貸方合計 ¥900。複式簿記では借方と貸方は必ず一致する必要があります。",
                      "success": false
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Validation error"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "example": {
                  "error": "Bank transaction not found",
                  "success": false
                },
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Bank transaction not found"
          },
          "423": {
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetails"
                }
              }
            },
            "description": "The bank row already carries 証憑 (a document link or a file), and the 仕訳 this call attaches to it is in a filed or closed 課税期間, including a quarter whose return is filed while its period row is still open (PERIOD_LOCKED). Allowed inside a 修正申告 for that fiscal year."
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create compound (multi-line) journal entry from bank transaction",
        "tags": [
          "Bank Reconciliation"
        ]
      }
    },
    "/reconciliation/create-compound-journal/preview": {
      "post": {
        "description": "Takes the same body as `POST /reconciliation/create-compound-journal` and writes nothing.\n\nReturns the books advisories (BE ADR-0015) the entry would raise, as ADR-0014 `Advisory` cases on the bank row —\nfor example a 仮払消費税 line split out of a purchase by a 税込経理 company (presentation only; the 控除税額 is\nunchanged when both lines are 課税). The bank / cash lines are not evaluated. Never blocks the post.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "bank_transaction_id": {
                    "description": "UUID of the bank transaction to link",
                    "example": "1a917c7d-c21a-4a10-ba8f-b8ac8adc38c0",
                    "format": "uuid",
                    "type": "string"
                  },
                  "category": {
                    "description": "Category code for the transaction",
                    "example": 4,
                    "type": "number"
                  },
                  "description": {
                    "description": "Overall journal entry description",
                    "example": "銀行利息（源泉徴収税込）",
                    "type": "string"
                  },
                  "entries": {
                    "description": "Journal entry lines (minimum 2)",
                    "example": [
                      {
                        "account_code": "102",
                        "account_name": "普通預金",
                        "credit_amount": 0,
                        "debit_amount": 851
                      },
                      {
                        "account_code": "137",
                        "account_name": "仮払法人税等",
                        "credit_amount": 0,
                        "debit_amount": 154
                      },
                      {
                        "account_code": "403",
                        "account_name": "受取利息",
                        "credit_amount": 1005,
                        "debit_amount": 0
                      }
                    ],
                    "items": {
                      "properties": {
                        "account_code": {
                          "description": "Account code (3-4 digits)",
                          "example": "102",
                          "type": "string"
                        },
                        "account_name": {
                          "description": "Account name (optional, for display)",
                          "example": "普通預金",
                          "type": "string"
                        },
                        "credit_amount": {
                          "description": "Credit amount (use 0 for debit-only line)",
                          "example": 0,
                          "type": "number"
                        },
                        "debit_amount": {
                          "description": "Debit amount (use 0 for credit-only line)",
                          "example": 851,
                          "type": "number"
                        },
                        "description": {
                          "description": "Line-specific description",
                          "example": "普通預金 利息",
                          "type": "string"
                        },
                        "tax_category": {
                          "description": "Per-line 消費税区分, persisted as journal_entry_lines.tax_code",
                          "example": "課税仕入10%",
                          "type": "string"
                        }
                      },
                      "required": [
                        "account_code",
                        "debit_amount",
                        "credit_amount"
                      ],
                      "type": "object"
                    },
                    "minItems": 2,
                    "type": "array"
                  },
                  "entry_type": {
                    "description": "Type of entry (used for validation and source_type)",
                    "enum": [
                      "interest_income",
                      "expense",
                      "revenue",
                      "other"
                    ],
                    "example": "interest_income",
                    "type": "string"
                  },
                  "is_ai_assisted": {
                    "description": "True when the AI bulk-journalize assistant generated the entry",
                    "type": "boolean"
                  }
                },
                "required": [
                  "bank_transaction_id",
                  "entries"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "advisories": {
                          "items": {
                            "$ref": "#/components/schemas/Advisory"
                          },
                          "type": "array"
                        },
                        "bankTransactionId": {
                          "format": "uuid",
                          "type": "string"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Advisories for the entry"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Books advisories for a compound bank entry, before it is posted (dry run)",
        "tags": [
          "Bank Reconciliation"
        ]
      }
    },
    "/reconciliation/create-expense/preview": {
      "post": {
        "description": "Runs the same account / 税区分 resolution as `POST /reconciliation/create-expense` without writing anything.\n\nReturns the two lines the server would post, which ledger account the bank side resolves to (the tenant's\nown most-used active 預金 account, or the chart constant when the tenant has no history), the 税区分 with\nits source (`request` / `history` / `backstop` / `account_default`), and human-readable warnings —\na retired duplicate code remapped by name, a code that would be auto-created, a tax code corrected by the\naccount backstop. The 取引処理 panel renders this under step C so the person sees the real posting before 完了.\n\n`advisories` carries the books advisories for the booking (BE ADR-0015) as ADR-0014 `Advisory` cases on the bank row — each with its rule, the action, the primary sources and any 確認記録 already recorded.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "account_code": {
                    "example": "514",
                    "type": "string"
                  },
                  "bank_transaction_id": {
                    "format": "uuid",
                    "type": "string"
                  },
                  "category": {
                    "type": "number"
                  },
                  "description": {
                    "type": "string"
                  },
                  "tax_type": {
                    "description": "Ledger tax_code 1–5; omit for 自動",
                    "type": "number"
                  }
                },
                "required": [
                  "bank_transaction_id",
                  "account_code"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "advisories": {
                          "description": "What a 税理士 would ask about this booking (ADR-0015): 建設仮勘定, 資本的支出, 事業供用日, 敷金の内訳, 売上の計上時期, 税込経理の税抜分割. Read before 完了; never blocks.",
                          "items": {
                            "$ref": "#/components/schemas/Advisory"
                          },
                          "type": "array"
                        },
                        "alreadyJournaled": {
                          "type": "boolean"
                        },
                        "amount": {
                          "type": "number"
                        },
                        "bank": {
                          "nullable": true,
                          "properties": {
                            "code": {
                              "type": "string"
                            },
                            "name": {
                              "type": "string"
                            },
                            "resolvedBy": {
                              "enum": [
                                "tenant_history",
                                "chart_constant",
                                "unknown"
                              ],
                              "type": "string"
                            }
                          },
                          "type": "object"
                        },
                        "bankTransactionId": {
                          "format": "uuid",
                          "type": "string"
                        },
                        "canPost": {
                          "type": "boolean"
                        },
                        "counter": {
                          "nullable": true,
                          "properties": {
                            "code": {
                              "type": "string"
                            },
                            "name": {
                              "type": "string"
                            },
                            "resolvedBy": {
                              "enum": [
                                "code",
                                "name",
                                "auto_create"
                              ],
                              "type": "string"
                            }
                          },
                          "type": "object"
                        },
                        "isWithdrawal": {
                          "type": "boolean"
                        },
                        "lines": {
                          "items": {
                            "properties": {
                              "accountCode": {
                                "type": "string"
                              },
                              "accountName": {
                                "type": "string"
                              },
                              "amount": {
                                "type": "number"
                              },
                              "side": {
                                "enum": [
                                  "debit",
                                  "credit"
                                ],
                                "type": "string"
                              },
                              "taxCode": {
                                "nullable": true,
                                "type": "number"
                              },
                              "taxLabel": {
                                "nullable": true,
                                "type": "string"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        },
                        "tax": {
                          "nullable": true,
                          "properties": {
                            "label": {
                              "nullable": true,
                              "type": "string"
                            },
                            "source": {
                              "enum": [
                                "request",
                                "history",
                                "backstop",
                                "account_default"
                              ],
                              "type": "string"
                            },
                            "taxCode": {
                              "type": "number"
                            }
                          },
                          "type": "object"
                        },
                        "warnings": {
                          "items": {
                            "type": "string"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Posting preview"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Preview what create-expense would post (dry run)",
        "tags": [
          "Bank Reconciliation"
        ]
      }
    },
    "/reconciliation/match": {
      "post": {
        "description": "Confirm a match between bank transaction and journal entry with optional adjustments.\n\n## Match Confirmation (照合確定)\nComprehensive matching with:\n- **Match Validation**: Thorough validation of match accuracy and completeness\n- **Adjustment Processing**: Automatic processing of reconciliation adjustments\n- **Journal Integration**: Seamless integration with journal entry system\n- **Audit Trail**: Complete audit trail for compliance and review\n- **Japanese Compliance**: Full compliance with Japanese accounting standards\n- **Error Handling**: Comprehensive error handling and rollback capabilities\n\n## Match Types Supported\n- **Exact Match**: Perfect amount and date alignment\n- **Amount Adjusted**: Match with transfer fees or other adjustments\n- **Partial Match**: Partial payment or receipt matching\n- **Combined Match**: Multiple journal entries to one bank transaction\n- **Split Match**: One journal entry to multiple bank transactions\n\n## Adjustment Processing\n- **Transfer Fees**: Automatic transfer fee calculation and posting\n- **FX Differences**: Foreign exchange gain/loss processing\n- **Withholding Tax**: Withholding tax calculation and posting\n- **Rounding**: Minor rounding difference handling\n- **Custom Adjustments**: User-defined adjustment processing\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "adjustments": {
                    "description": "Adjustments to apply for reconciliation differences",
                    "items": {
                      "properties": {
                        "account_code": {
                          "type": "string"
                        },
                        "amount": {
                          "format": "decimal",
                          "type": "number"
                        },
                        "description": {
                          "type": "string"
                        },
                        "type": {
                          "$ref": "#/components/schemas/AdjustmentType"
                        }
                      },
                      "type": "object"
                    },
                    "type": "array"
                  },
                  "bank_amount_applied": {
                    "description": "Amount from bank transaction to apply",
                    "format": "decimal",
                    "type": "number"
                  },
                  "bank_transaction_id": {
                    "description": "Bank transaction ID to match",
                    "format": "uuid",
                    "type": "string"
                  },
                  "journal_amount_applied": {
                    "description": "Amount from journal entry to apply",
                    "format": "decimal",
                    "type": "number"
                  },
                  "journal_entry_id": {
                    "description": "Journal entry ID to match with",
                    "format": "uuid",
                    "type": "string"
                  },
                  "match_type": {
                    "$ref": "#/components/schemas/MatchType"
                  }
                },
                "required": [
                  "bank_transaction_id",
                  "journal_entry_id",
                  "match_type",
                  "bank_amount_applied",
                  "journal_amount_applied"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ReconciliationActionResponse"
                }
              }
            },
            "description": "Match confirmed successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "409": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Transaction already reconciled or amounts do not balance",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Match conflict or validation error"
          },
          "423": {
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/ProblemDetails"
                }
              }
            },
            "description": "The bank row already carries 証憑 (a document link or a file), and the 仕訳 this call attaches to it is in a filed or closed 課税期間, including a quarter whose return is filed while its period row is still open (PERIOD_LOCKED). Allowed inside a 修正申告 for that fiscal year."
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Confirm reconciliation match",
        "tags": [
          "Bank Reconciliation"
        ]
      }
    },
    "/reconciliation/patterns": {
      "get": {
        "description": "Retrieve detected transaction patterns for automated rule creation and reconciliation optimization.\n\n## Pattern Detection (パターン検出)\nMachine learning-based pattern detection with:\n- **Frequency Analysis**: Detect recurring transaction patterns and frequencies\n- **Amount Patterns**: Identify consistent amount patterns and variations\n- **Description Analysis**: Analyze transaction descriptions for common patterns\n- **Counterparty Patterns**: Detect recurring counterparty transaction patterns\n- **Rule Suggestions**: Generate rule suggestions based on detected patterns\n\n## Pattern Types\n- **Recurring Transactions**: Monthly, quarterly, or yearly recurring patterns\n- **Amount Clusters**: Groups of transactions with similar amounts\n- **Description Patterns**: Common description patterns and keywords\n- **Timing Patterns**: Patterns in transaction timing and frequency\n- **Counterparty Patterns**: Recurring counterparty transaction patterns\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ReconciliationPatternsResponse"
                }
              }
            },
            "description": "Reconciliation patterns retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get detected reconciliation patterns",
        "tags": [
          "Bank Reconciliation"
        ]
      }
    },
    "/reconciliation/rules": {
      "get": {
        "description": "Retrieve all reconciliation rules for the authenticated user with usage statistics.\n\n## Reconciliation Rules (照合ルール)\nAutomated rule management with:\n- **Rule Definition**: Comprehensive rule definition with match criteria and actions\n- **Priority Management**: Rule execution priority for optimal matching order\n- **Usage Statistics**: Track rule application frequency and effectiveness\n- **Pattern Integration**: Integration with detected transaction patterns\n- **Performance Monitoring**: Monitor rule performance and success rates\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ReconciliationRulesResponse"
                }
              }
            },
            "description": "Reconciliation rules retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get reconciliation rules",
        "tags": [
          "Bank Reconciliation"
        ]
      },
      "post": {
        "description": "Create a new reconciliation rule for automated matching.\n\n## Rule Creation (ルール作成)\nComprehensive rule creation with:\n- **Match Criteria**: Define complex matching criteria with multiple conditions\n- **Action Configuration**: Configure actions to perform when rule matches\n- **Priority Setting**: Set rule execution priority for optimal performance\n- **Validation**: Comprehensive validation of rule logic and configuration\n- **Testing**: Built-in rule testing capabilities before activation\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "action_config": {
                    "type": "object"
                  },
                  "action_type": {
                    "maxLength": 20,
                    "type": "string"
                  },
                  "description": {
                    "type": "string"
                  },
                  "match_criteria": {
                    "type": "object"
                  },
                  "name": {
                    "maxLength": 100,
                    "type": "string"
                  },
                  "priority": {
                    "maximum": 999,
                    "minimum": 1,
                    "type": "integer"
                  }
                },
                "required": [
                  "name",
                  "match_criteria",
                  "action_type"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ReconciliationActionResponse"
                }
              }
            },
            "description": "Reconciliation rule created successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create reconciliation rule",
        "tags": [
          "Bank Reconciliation"
        ]
      }
    },
    "/reconciliation/suggestions/{bankTxId}": {
      "get": {
        "description": "Get intelligent match suggestions for a specific bank transaction with confidence scoring.\n\n## Match Suggestions (照合候補)\nAI-powered matching with:\n- **Confidence Scoring**: Machine learning-based confidence scores (0.0 to 1.0)\n- **Multiple Match Types**: Exact, amount adjusted, partial, combined, and split matches\n- **Adjustment Suggestions**: Intelligent adjustment suggestions for differences\n- **Japanese Standards**: Compliance with Japanese banking and accounting standards\n- **Rule-Based Matching**: Integration with user-defined reconciliation rules\n- **Pattern Recognition**: Historical pattern-based suggestion enhancement\n\n## Suggestion Algorithm\n- **Exact Matching**: Perfect amount and date matches with high confidence\n- **Fuzzy Matching**: Similar amounts and dates with description analysis\n- **Rule-Based**: Matches based on user-defined reconciliation rules\n- **Pattern-Based**: Matches based on detected recurring patterns\n- **Adjustment Handling**: Automatic adjustment suggestions for common differences\n\n## Adjustment Types\n- **Transfer Fees**: Japanese bank transfer fee adjustments\n- **FX Gains/Losses**: Foreign exchange difference handling\n- **Withholding Tax**: Automatic withholding tax calculations (10.21%)\n- **Rounding Differences**: Minor rounding adjustments\n- **Discounts**: Early payment discounts and promotional adjustments\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Bank transaction ID to get suggestions for",
            "in": "path",
            "name": "bankTxId",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Maximum number of suggestions to return",
            "in": "query",
            "name": "limit",
            "required": false,
            "schema": {
              "default": 10,
              "maximum": 50,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "description": "Minimum confidence threshold for suggestions",
            "in": "query",
            "name": "min_confidence",
            "required": false,
            "schema": {
              "default": 0.1,
              "maximum": 1,
              "minimum": 0,
              "type": "number"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MatchSuggestionsResponse"
                }
              }
            },
            "description": "Match suggestions retrieved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Bank transaction not found",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Bank transaction not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get match suggestions for bank transaction",
        "tags": [
          "Bank Reconciliation"
        ]
      }
    },
    "/reconciliation/unreconciled": {
      "get": {
        "description": "Retrieve paginated list of unreconciled bank transactions with comprehensive filtering options.\n\n## Unreconciled Transactions (未照合取引)\nAdvanced transaction management with:\n- **Intelligent Filtering**: Filter by date range, bank account, and reconciliation status\n- **Match Suggestions**: Pre-calculated match suggestion counts for each transaction\n- **Aging Analysis**: Days unreconciled for prioritizing older transactions\n- **Status Tracking**: Comprehensive status tracking (pending, excluded, suspense)\n- **Japanese Banking**: Full support for Japanese banking transaction formats\n- **Performance Optimization**: Efficient pagination for large transaction volumes\n\n## Filtering Capabilities\n- **Date Range**: Filter transactions by specific date ranges (YYYYMMDD format)\n- **Bank Account**: Filter by specific bank account for multi-account reconciliation\n- **Status Filter**: Filter by reconciliation status for workflow management\n- **Pagination**: Efficient pagination with configurable page sizes\n\n## Transaction Information\n- **Transaction Details**: Complete transaction information with amounts and descriptions\n- **Counterparty Data**: Japanese counterparty names and banking details\n- **Match Readiness**: Pre-calculated match suggestion counts for efficiency\n- **Aging Information**: Days unreconciled for prioritization and workflow management\n\n## Use Cases\n- **Daily Reconciliation**: Daily review of new unreconciled transactions\n- **Month-End Processing**: Comprehensive month-end reconciliation workflows\n- **Audit Preparation**: Organize unreconciled items for audit review\n- **Cash Flow Management**: Monitor unreconciled items affecting cash flow\n- **Workflow Prioritization**: Prioritize reconciliation work based on aging and amounts\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Number of transactions per page",
            "in": "query",
            "name": "page_size",
            "required": false,
            "schema": {
              "default": 20,
              "maximum": 100,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "description": "Page number for pagination",
            "in": "query",
            "name": "page_number",
            "required": false,
            "schema": {
              "default": 1,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "description": "Start date filter in YYYYMMDD format",
            "example": 20240101,
            "in": "query",
            "name": "start_date",
            "required": false,
            "schema": {
              "maximum": 99991231,
              "minimum": 19700101,
              "type": "integer"
            }
          },
          {
            "description": "End date filter in YYYYMMDD format",
            "example": 20240131,
            "in": "query",
            "name": "end_date",
            "required": false,
            "schema": {
              "maximum": 99991231,
              "minimum": 19700101,
              "type": "integer"
            }
          },
          {
            "description": "Filter by specific bank account ID",
            "in": "query",
            "name": "bank_account_id",
            "required": false,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Filter by reconciliation status",
            "in": "query",
            "name": "status",
            "required": false,
            "schema": {
              "$ref": "#/components/schemas/ReconciliationStatus"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/UnreconciledTransactionsResponse"
                }
              }
            },
            "description": "Unreconciled transactions retrieved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get unreconciled bank transactions",
        "tags": [
          "Bank Reconciliation"
        ]
      }
    },
    "/reconciliation/validate/{year}/{month}": {
      "get": {
        "description": "Perform comprehensive month-end reconciliation validation for audit and compliance.\n\n## Month-End Validation (月末検証)\nComprehensive validation with:\n- **Reconciliation Completeness**: Verify all transactions are properly reconciled\n- **Balance Verification**: Ensure all balances are accurate and complete\n- **Audit Compliance**: Generate audit-ready reconciliation reports\n- **Issue Detection**: Identify and report reconciliation issues and discrepancies\n- **Recommendations**: Provide recommendations for improving reconciliation processes\n\n## Validation Checks\n- **Completeness**: Verify all transactions have been addressed\n- **Accuracy**: Validate mathematical accuracy of all reconciliations\n- **Compliance**: Ensure compliance with Japanese accounting standards\n- **Aging Analysis**: Analyze aging of unreconciled items\n- **Risk Assessment**: Assess risk levels of unreconciled amounts\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Year for validation (YYYY format)",
            "in": "path",
            "name": "year",
            "required": true,
            "schema": {
              "maximum": 2099,
              "minimum": 2020,
              "type": "integer"
            }
          },
          {
            "description": "Month for validation (1-12)",
            "in": "path",
            "name": "month",
            "required": true,
            "schema": {
              "maximum": 12,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MonthEndValidationResponse"
                }
              }
            },
            "description": "Month-end validation completed successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Validate month-end reconciliation",
        "tags": [
          "Bank Reconciliation"
        ]
      }
    },
    "/reference-data": {
      "get": {
        "description": "Get comprehensive reference data for frontend application initialization and caching.\n\n## Reference Data Holder Pattern\nCentralized reference data management with:\n- **Single Source of Truth**: Centralized location for all business lookup data\n- **Frontend Initialization**: Complete data set for application startup and caching\n- **Static Data Optimization**: Optimized for caching with appropriate HTTP headers\n- **Internationalization**: Japanese and English labels for all reference values\n- **Business Context**: Complete business reference data for Japanese accounting\n\n## Comprehensive Data Categories\n- **Expense Categories**: Complete expense classification with account codes\n- **Document Types**: Business document types with workflow information\n- **Payment Methods**: Payment method options with validation rules\n- **Tax Types**: Japanese tax classifications with rates and descriptions\n- **Withholding Categories**: Withholding tax categories with official rates\n- **Status Enums**: Various status enums with colors and workflow transitions\n- **Asset Classifications**: Fixed asset types with depreciation information\n- **Chart of Accounts**: Dynamic account data from database\n\n## Caching Strategy\n- **HTTP Caching**: 1-hour cache headers for optimal performance\n- **Static Nature**: Data is relatively static and safe for aggressive caching\n- **Cache Invalidation**: Manual cache invalidation when reference data changes\n- **Frontend Caching**: Designed for frontend caching on application initialization\n\n## Data Structure\n- **Consistent Format**: All enum items follow consistent structure with value, label, labelEn\n- **Extended Properties**: Additional properties like rates, colors, formulas where applicable\n- **Metadata**: Version information and generation timestamps\n- **Internationalization**: Full Japanese and English label support\n\n## Use Cases\n- **Application Initialization**: Load all reference data on application startup\n- **Dropdown Population**: Populate dropdowns and selection lists\n- **Validation**: Validate user inputs against reference data\n- **Internationalization**: Support multiple languages in UI\n- **Business Logic**: Support business logic with proper classifications\n\n## Performance Optimization\n- **Single Request**: Get all data in one request to minimize round trips\n- **Caching**: Aggressive caching for static data\n- **Efficient Structure**: Optimized data structures for frontend consumption\n- **Minimal Payload**: Efficient data format without unnecessary overhead\n\nNo authentication required for public reference data.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AllReferenceDataResponse"
                }
              }
            },
            "description": "All reference data retrieved successfully",
            "headers": {
              "Cache-Control": {
                "description": "Cache control header for optimization",
                "schema": {
                  "example": "public, max-age=3600",
                  "type": "string"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "Get all reference data for application initialization",
        "tags": [
          "Reference Data"
        ]
      }
    },
    "/reference-data/accounts": {
      "get": {
        "description": "Get chart of accounts with optional filtering by type and category.\n\n## Chart of Accounts (勘定科目)\nDynamic account data with:\n- **Database Integration**: Real-time data from chart of accounts database\n- **Flexible Filtering**: Filter by account type and category\n- **Complete Information**: Account codes, names, types, and categories\n- **Bilingual Support**: Japanese and English account names\n- **Business Classification**: Proper classification for Japanese accounting\n\n## Account Types\n- **Asset (資産)**: Asset accounts including current and fixed assets\n- **Liability (負債)**: Liability accounts including current and long-term liabilities\n- **Equity (純資産)**: Equity accounts including capital and retained earnings\n- **Revenue (収益)**: Revenue and income accounts\n- **Expense (費用)**: Expense accounts including operating and non-operating expenses\n\n## Account Categories\n- **Current Assets (流動資産)**: Cash, receivables, inventory\n- **Fixed Assets (固定資産)**: Property, equipment, intangible assets\n- **Current Liabilities (流動負債)**: Payables, accrued expenses, short-term debt\n- **Long-term Liabilities (固定負債)**: Long-term debt, deferred tax liabilities\n- **Operating Expenses (営業費用)**: Cost of goods sold, operating expenses\n- **Administrative Expenses (販売費及び一般管理費)**: Selling and administrative expenses\n\n## Filtering Options\n- **Type Filter**: Filter accounts by type (asset, liability, equity, revenue, expense)\n- **Category Filter**: Filter accounts by specific categories within types\n- **Combined Filtering**: Use both type and category filters together\n- **No Filter**: Get all accounts when no filters specified\n\n## Use Cases\n- **Account Selection**: Populate account selection dropdowns\n- **Journal Entry**: Support journal entry account selection\n- **Financial Reporting**: Support financial report generation\n- **Account Validation**: Validate account codes and names\n- **Chart Management**: Support chart of accounts management\n\n## Data Format\n- **Standard Structure**: Consistent account data structure\n- **Account Codes**: Standard Japanese account code format\n- **Bilingual Names**: Both Japanese and English account names\n- **Type Classification**: Clear type and category classification\n- **Database Sync**: Real-time synchronization with account database\n\nNo authentication required for chart of accounts data.",
        "parameters": [
          {
            "description": "Filter by account type",
            "example": "expense",
            "in": "query",
            "name": "type",
            "required": false,
            "schema": {
              "enum": [
                "asset",
                "liability",
                "equity",
                "revenue",
                "expense"
              ],
              "type": "string"
            }
          },
          {
            "description": "Filter by account category",
            "example": "販売費及び一般管理費",
            "in": "query",
            "name": "category",
            "required": false,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AccountsResponse"
                }
              }
            },
            "description": "Chart of accounts retrieved successfully"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "Get chart of accounts from database",
        "tags": [
          "Reference Data"
        ]
      }
    },
    "/reference-data/banks": {
      "get": {
        "description": "Get a searchable list of Japanese banks with Zengin codes.\n\n## Features\n- **Search**: Filter by bank name (kanji, kana, or romaji)\n- **Category filter**: Filter by bank category (city, trust, regional, etc.)\n- **100+ banks**: Comprehensive list of major Japanese financial institutions\n\n## Categories\n- `city`: 都市銀行 (City banks - MUFG, SMBC, Mizuho, Resona)\n- `trust`: 信託銀行 (Trust banks)\n- `regional`: 地方銀行 (Regional banks)\n- `second_regional`: 第二地方銀行 (Second-tier regional banks)\n- `shinkin`: 信用金庫 (Credit associations)\n- `net`: ネット銀行 (Online banks)\n- `other`: その他 (Others - Japan Post, JA, etc.)\n\n## Caching\n- **7-day HTTP cache**: `Cache-Control: public, max-age=604800, s-maxage=604800`\n- Bank data is very stable and rarely changes",
        "parameters": [
          {
            "description": "Search by bank name (kanji, kana, or romaji)",
            "in": "query",
            "name": "search",
            "required": false,
            "schema": {
              "example": "みずほ",
              "type": "string"
            }
          },
          {
            "description": "Filter by bank category",
            "in": "query",
            "name": "category",
            "required": false,
            "schema": {
              "enum": [
                "city",
                "trust",
                "regional",
                "second_regional",
                "shinkin",
                "net",
                "other"
              ],
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "items": {
                        "properties": {
                          "bank_code": {
                            "example": "0001",
                            "type": "string"
                          },
                          "category": {
                            "example": "city",
                            "type": "string"
                          },
                          "name": {
                            "example": "みずほ銀行",
                            "type": "string"
                          },
                          "name_kana": {
                            "example": "ミズホギンコウ",
                            "type": "string"
                          },
                          "name_romaji": {
                            "example": "Mizuho Bank",
                            "type": "string"
                          },
                          "short_name": {
                            "example": "みずほ",
                            "type": "string"
                          }
                        },
                        "type": "object"
                      },
                      "type": "array"
                    },
                    "message": {
                      "example": "銀行一覧を取得しました",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Banks list retrieved successfully",
            "headers": {
              "Cache-Control": {
                "description": "7-day cache",
                "schema": {
                  "example": "public, max-age=604800, s-maxage=604800",
                  "type": "string"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "Get Japanese banks list (銀行一覧)",
        "tags": [
          "Reference Data"
        ]
      }
    },
    "/reference-data/enum/{enumName}": {
      "get": {
        "description": "Get a specific enum by name for targeted data retrieval.\n\n## Specific Enum Retrieval\nTargeted enum access with:\n- **Specific Data**: Get only the enum data you need\n- **Extended Caching**: 24-hour cache for individual enums\n- **Error Handling**: Clear error messages with available enum list\n- **Flexible Access**: Access any registered enum by name\n- **Performance Optimization**: Reduced payload for specific needs\n\n## Available Enums\n- **expenseCategories**: Expense classification with account codes\n- **documentTypes**: Business document types and workflows\n- **paymentMethods**: Payment method options and validation\n- **taxTypes**: Tax classifications with rates\n- **withholdingCategories**: Withholding tax categories and rates\n- **payeeTypes**: Payee classifications with withholding requirements\n- **fiscalPeriodStatuses**: Fiscal period status workflow\n- **reconciliationStatuses**: Reconciliation status with UI colors\n- **expenseReportStatuses**: Expense report workflow statuses\n- **fixedAssetClassifications**: Asset types with depreciation info\n- **depreciationMethods**: Depreciation calculation methods\n- **journalEntryStatuses**: Journal entry status with editability\n- **reminderTypes**: Reminder classifications with frequencies\n\n## Caching Strategy\n- **Extended Caching**: 24-hour cache for individual enums\n- **Static Nature**: Individual enums are highly static\n- **Performance**: Optimized for repeated access to specific enums\n- **Cache Headers**: Appropriate HTTP cache headers for browser caching\n\n## Use Cases\n- **Specific Needs**: When only specific enum data is needed\n- **Lazy Loading**: Load enum data on demand\n- **Reduced Bandwidth**: Minimize data transfer for mobile applications\n- **Targeted Updates**: Update specific enum data without full reload\n\n## Error Handling\n- **Not Found**: Clear error message with list of available enums\n- **Suggestions**: Provides list of valid enum names for correction\n- **Helpful Errors**: Error responses include actionable information\n\nNo authentication required for public reference data.",
        "parameters": [
          {
            "description": "Name of the enum to retrieve",
            "example": "expenseCategories",
            "in": "path",
            "name": "enumName",
            "required": true,
            "schema": {
              "enum": [
                "expenseCategories",
                "documentTypes",
                "paymentMethods",
                "taxTypes",
                "withholdingCategories",
                "payeeTypes",
                "fiscalPeriodStatuses",
                "reconciliationStatuses",
                "expenseReportStatuses",
                "fixedAssetClassifications",
                "depreciationMethods",
                "journalEntryStatuses",
                "reminderTypes"
              ],
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/EnumResponse"
                }
              }
            },
            "description": "Enum retrieved successfully",
            "headers": {
              "Cache-Control": {
                "description": "Cache control header for optimization",
                "schema": {
                  "example": "public, max-age=86400",
                  "type": "string"
                }
              }
            }
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/EnumNotFoundResponse"
                }
              }
            },
            "description": "Enum not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "Get specific enum by name",
        "tags": [
          "Reference Data"
        ]
      }
    },
    "/reference-data/expense-categories": {
      "get": {
        "description": "Get expense categories with associated account codes for expense management.\n\n## Expense Categories (経費カテゴリ)\nComprehensive expense classification with:\n- **Complete Classification**: All major expense categories for Japanese businesses\n- **Account Mapping**: Direct mapping to chart of accounts codes\n- **Bilingual Labels**: Japanese and English labels for internationalization\n- **Business Context**: Descriptions and usage guidelines for each category\n- **Accounting Integration**: Ready for integration with accounting systems\n\n## Category Coverage\n- **Entertainment (接待交際費)**: Business entertainment and client relations\n- **Meeting Expenses (会議費)**: Internal and external meeting costs\n- **Office Supplies (事務用品費)**: Office supplies and stationery\n- **Travel & Transport (旅費交通費)**: Business travel and transportation\n- **Advertising (広告宣伝費)**: Marketing and advertising expenses\n- **Utilities (水道光熱費)**: Utility costs (electricity, gas, water)\n- **Rent (賃借料)**: Office and facility rental costs\n- **Communication (通信費)**: Telecommunications and internet costs\n- **Outsourcing (外注費)**: External contractor and outsourcing costs\n- **Supplies (消耗品費)**: Consumable supplies and materials\n- **Repairs (修繕費)**: Maintenance and repair costs\n- **Insurance (保険料)**: Various insurance premiums\n- **Training (研修費)**: Training and education expenses\n- **Professional Fees (支払手数料)**: Legal, accounting, and professional fees\n- **Equipment (備品費)**: Equipment and furniture purchases\n- **Fuel (燃料費)**: Vehicle fuel costs\n- **Pre-establishment (開業費)**: Pre-opening business expenses\n\n## Account Code Integration\n- **Direct Mapping**: Each category maps to specific account codes\n- **Japanese Standards**: Follows Japanese chart of accounts standards\n- **Consistency**: Consistent account code assignments\n- **Automation**: Enables automated account assignment based on category\n\n## Extended Caching\n- **24-Hour Cache**: Extended caching for stable expense category data\n- **Performance**: Optimized for repeated access\n- **Static Nature**: Expense categories change infrequently\n\nNo authentication required for expense category reference data.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExpenseCategoriesResponse"
                }
              }
            },
            "description": "Expense categories retrieved successfully",
            "headers": {
              "Cache-Control": {
                "description": "Cache control header for optimization",
                "schema": {
                  "example": "public, max-age=86400",
                  "type": "string"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "Get expense categories with account mappings",
        "tags": [
          "Reference Data"
        ]
      }
    },
    "/reference-data/holidays/{year}": {
      "get": {
        "description": "Get Japanese national holidays for a specific year.\n\n## Available Years\n2024-2030 (pre-computed static data)\n\n## Caching\n- **30-day HTTP cache**: `Cache-Control: public, max-age=2592000, s-maxage=2592000`\n- Holiday data is static and determined by law",
        "parameters": [
          {
            "description": "Year to get holidays for (2024-2030)",
            "in": "path",
            "name": "year",
            "required": true,
            "schema": {
              "example": 2026,
              "maximum": 2030,
              "minimum": 2024,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "count": {
                          "example": 16,
                          "type": "integer"
                        },
                        "holidays": {
                          "items": {
                            "properties": {
                              "date": {
                                "example": "2026-01-01",
                                "type": "string"
                              },
                              "name": {
                                "example": "元日",
                                "type": "string"
                              },
                              "name_en": {
                                "example": "New Year's Day",
                                "type": "string"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        },
                        "year": {
                          "example": 2026,
                          "type": "integer"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "2026年の祝日一覧を取得しました",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Holidays retrieved successfully",
            "headers": {
              "Cache-Control": {
                "description": "30-day cache",
                "schema": {
                  "example": "public, max-age=2592000, s-maxage=2592000",
                  "type": "string"
                }
              }
            }
          },
          "400": {
            "description": "Invalid year (must be 2024-2030)"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "Get Japanese national holidays (祝日一覧)",
        "tags": [
          "Reference Data"
        ]
      }
    },
    "/reference-data/tax-rates/current": {
      "get": {
        "description": "Get the current effective tax rate schedule from the database.\n\n## Tax Rate Schedule (税率スケジュール)\nReturns versioned tax rates with effective dates for:\n- **Corporate Tax (法人税)**: Standard and reduced rates by taxable income brackets\n- **Consumption Tax (消費税)**: Standard and reduced rates\n- **Withholding Tax (源泉徴収)**: Rates by income type and residency\n- **Inhabitants Tax (住民税)**: Municipal and prefectural rates\n\n## Caching\n- **24-hour HTTP cache**: `Cache-Control: public, max-age=86400, s-maxage=86400`\n- **In-memory cache**: Service-level caching for performance\n- Tax rates change at most once per fiscal year\n\n## Data Source\nRates are stored in the `tax_rate_schedules` table with:\n- `effective_date`: When rates became effective\n- `fiscal_year_label`: Human-readable label (e.g., \"令和6年度\")\n- `rates`: Full JSON structure of all tax rates\n- `is_active`: Whether this schedule is currently active",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "effective_date": {
                          "example": "2024-04-01",
                          "format": "date",
                          "type": "string"
                        },
                        "fiscal_year_label": {
                          "example": "令和6年度 (FY2024)",
                          "type": "string"
                        },
                        "rates": {
                          "description": "Complete tax rate structure with corporate, consumption, withholding, and inhabitants tax rates",
                          "type": "object"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "現行税率を取得しました",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Current tax rates retrieved successfully",
            "headers": {
              "Cache-Control": {
                "description": "24-hour cache",
                "schema": {
                  "example": "public, max-age=86400, s-maxage=86400",
                  "type": "string"
                }
              }
            }
          },
          "404": {
            "description": "No active tax rate schedule found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "Get current tax rate schedule (現行税率取得)",
        "tags": [
          "Reference Data"
        ]
      }
    },
    "/reference-data/validate": {
      "get": {
        "description": "Validate whether a value is valid for a specific enum.\n\n## Enum Validation\nComprehensive validation service with:\n- **Value Validation**: Check if value exists in specified enum\n- **Label Retrieval**: Get human-readable label for valid values\n- **Error Feedback**: Clear validation results with explanations\n- **Multi-Format Support**: Support for both string and integer enum values\n- **Internationalization**: Label retrieval in Japanese or English\n\n## Validation Process\n1. **Enum Lookup**: Find the specified enum by name\n2. **Value Search**: Search for the value in enum items\n3. **Match Detection**: Check both value and code fields for matches\n4. **Label Retrieval**: Retrieve appropriate label if value is valid\n5. **Result Generation**: Generate validation result with details\n\n## Supported Validation\n- **String Values**: Validate string-based enum values\n- **Integer Values**: Validate integer-based enum values\n- **Code Matching**: Match against both value and code fields\n- **Case Sensitivity**: Proper case-sensitive matching\n- **Type Safety**: Ensure type safety in validation\n\n## Use Cases\n- **Form Validation**: Validate form inputs against reference data\n- **Data Import**: Validate imported data against business rules\n- **API Validation**: Validate API parameters before processing\n- **Data Integrity**: Ensure data integrity in business operations\n- **User Feedback**: Provide immediate feedback on data entry\n\n## Response Information\n- **Validation Result**: Boolean result indicating validity\n- **Value Echo**: Echo back the validated value for confirmation\n- **Label Information**: Human-readable label for valid values\n- **Error Context**: Context information for invalid values\n\nNo authentication required for validation utilities.",
        "parameters": [
          {
            "description": "Name of the enum to validate against",
            "example": "expenseCategories",
            "in": "query",
            "name": "enumName",
            "required": true,
            "schema": {
              "enum": [
                "expenseCategories",
                "documentTypes",
                "paymentMethods",
                "taxTypes",
                "withholdingCategories",
                "payeeTypes",
                "fiscalPeriodStatuses",
                "reconciliationStatuses",
                "expenseReportStatuses",
                "fixedAssetClassifications",
                "depreciationMethods",
                "journalEntryStatuses",
                "reminderTypes"
              ],
              "type": "string"
            }
          },
          {
            "description": "Value to validate",
            "example": "draft",
            "in": "query",
            "name": "value",
            "required": true,
            "schema": {
              "oneOf": [
                {
                  "type": "string"
                },
                {
                  "type": "integer"
                }
              ]
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ValidationResponse"
                }
              }
            },
            "description": "Validation completed successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "example": null,
                      "type": "null"
                    },
                    "message": {
                      "example": "enumName and value are required query parameters",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Missing required parameters"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "Validate enum value",
        "tags": [
          "Reference Data"
        ]
      }
    },
    "/reference-data/withholding": {
      "get": {
        "description": "Get comprehensive withholding tax reference data including categories and payee types.\n\n## Withholding Tax Reference (源泉徴収参照データ)\nComplete withholding tax information with:\n- **Tax Categories**: All withholding tax categories with official rates\n- **Payee Types**: Payee classifications with withholding requirements\n- **Rate Information**: Official Japanese withholding tax rates\n- **Legal Compliance**: Full compliance with Japanese withholding tax law\n- **Business Integration**: Ready for integration with payroll and payment systems\n\n## Withholding Categories\n- **Professional Fees (報酬・料金等)**: 10.21% rate for freelance and professional services\n- **Royalties (使用料等)**: 10.21% rate for intellectual property usage\n- **Rent (不動産賃料)**: 10.21% rate for real estate rental income\n- **Dividends (配当等)**: 20.42% rate for dividend payments\n- **Interest (利子)**: 15.21% rate for interest payments\n- **Prizes (賞金・賞品)**: 10.21% rate for contest prizes and awards\n- **Retirement (退職金)**: Special calculation for retirement income\n- **Other (その他)**: 10.21% rate for other withholding situations\n\n## Payee Types\n- **Individual (個人)**: Individual persons requiring withholding\n- **Corporation (法人)**: Corporate entities (generally no withholding)\n- **Sole Proprietor (個人事業主)**: Individual business owners requiring withholding\n- **Foreign Entity (国外事業者)**: Foreign businesses with special withholding rules\n\n## Legal Compliance\n- **Official Rates**: Uses official Japanese withholding tax rates\n- **Legal Categories**: Categories based on Japanese tax law classifications\n- **Compliance Requirements**: Information about withholding requirements by payee type\n- **Rate Updates**: Rates updated according to Japanese tax law changes\n\n## Use Cases\n- **Payroll Processing**: Calculate withholding tax for employee payments\n- **Vendor Payments**: Determine withholding requirements for vendor payments\n- **Tax Compliance**: Ensure compliance with Japanese withholding tax law\n- **Payment Systems**: Integrate withholding calculations into payment processing\n- **Reporting**: Support withholding tax reporting and documentation\n\n## Extended Caching\n- **24-Hour Cache**: Extended caching for stable withholding tax data\n- **Performance**: Optimized for payroll and payment system integration\n- **Legal Stability**: Withholding rates and categories change infrequently\n\nNo authentication required for withholding tax reference data.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/WithholdingDataResponse"
                }
              }
            },
            "description": "Withholding tax reference data retrieved successfully",
            "headers": {
              "Cache-Control": {
                "description": "Cache control header for optimization",
                "schema": {
                  "example": "public, max-age=86400",
                  "type": "string"
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "summary": "Get withholding tax reference data",
        "tags": [
          "Reference Data"
        ]
      }
    },
    "/referrals/me": {
      "get": {
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/ReferralCodeResponse"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "OK"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get the authenticated user's referral code, share URL, and stats",
        "tags": [
          "Referrals"
        ]
      }
    },
    "/referrals/redeem": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/RedeemReferralRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "description": "Pending row created (or idempotent re-call)"
          },
          "400": {
            "description": "Self-referral or invalid code format"
          },
          "404": {
            "description": "Referral code not found"
          },
          "409": {
            "description": "Referee already redeemed a different code"
          },
          "422": {
            "description": "Disposable email domain rejected"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Redeem a referral code (called once after signup)",
        "tags": [
          "Referrals"
        ]
      }
    },
    "/referrals/validate/{code}": {
      "get": {
        "parameters": [
          {
            "in": "path",
            "name": "code",
            "required": true,
            "schema": {
              "pattern": "^[A-HJ-KM-NP-Z2-9]{8}$",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "referrerDisplayName": {
                          "example": "田〇〇",
                          "nullable": true,
                          "type": "string"
                        },
                        "valid": {
                          "type": "boolean"
                        }
                      },
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "OK"
          }
        },
        "summary": "Validate a referral code and return masked referrer name (public)",
        "tags": [
          "Referrals"
        ]
      }
    },
    "/reimbursement/link/claims-to-payment": {
      "post": {
        "description": "Create a relationship between claims and payment documents to complete the reimbursement workflow.\n\n## Claims-to-Payment Linking\nEstablishes the final stage of Japanese reimbursement workflow:\n- **Document Relationship**: Creates parent-child relationship between claims and payment\n- **Expense References**: Creates payment references for all expenses in claims\n- **Workflow Completion**: Advances workflow from claims stage to payment stage\n- **Payment Processing**: Enables payment processing and approval workflow\n\n## Payment Reference Creation\nWhen linking claims to payment:\n- **Expense Identification**: All expenses from claims document are processed\n- **Payment References**: Expense references created in payment document with 'payment' role\n- **Amount Validation**: Payment amounts validated against claims totals\n- **Approval Workflow**: Payment document prepared for approval process\n\n## Workflow Completion\n- **Stage Progression**: Workflow advances from 経費 (Claims) to 支払 (Payment)\n- **Progress Update**: Workflow marked as near completion\n- **Document Finalization**: Claims document marked as linked to payment\n- **Audit Completion**: Complete audit trail for reimbursement process\n\n## Payment Processing Integration\n- **Approval Workflow**: Payment document ready for management approval\n- **Bank Integration**: Payment information prepared for bank processing\n- **Receipt Generation**: Payment receipts and confirmations available\n- **Accounting Integration**: Payment data available for accounting systems\n\n## Validation Rules\n- **Document Types**: Claims document must be 'claims' type, payment must be 'payment' type\n- **User Ownership**: User must own both documents\n- **Claims Status**: Claims document must be in approved status\n- **Amount Consistency**: Payment amounts must match or be subset of claims amounts\n\n## Use Cases\n- **Payment Authorization**: Prepare claims for payment processing\n- **Workflow Completion**: Complete reimbursement workflow cycle\n- **Audit Trail**: Maintain complete documentation for payments\n- **Accounting Integration**: Enable accounting system integration for payments\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "link_claims_to_payment": {
                  "summary": "Link claims document to payment document",
                  "value": {
                    "claims_document_id": "456e7890-f12a-34b5-c678-901234567890",
                    "payment_document_id": "abc12345-def6-7890-ghij-klmnopqrstuv"
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/LinkClaimsToPaymentRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DocumentLinkResponse"
                }
              }
            },
            "description": "Claims document linked to payment document successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Invalid document IDs or documents already linked",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid request or validation errors"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Link claims document to payment document",
        "tags": [
          "Reimbursement Workflow"
        ]
      }
    },
    "/reimbursement/link/travel-to-claims": {
      "post": {
        "description": "Create a relationship between a travel report and claims document with automatic expense synchronization.\n\n## Travel-to-Claims Linking\nEstablishes the first stage of Japanese reimbursement workflow:\n- **Document Relationship**: Creates parent-child relationship between travel and claims\n- **Expense Synchronization**: Automatically syncs expenses from travel report to claims\n- **Workflow Progression**: Advances workflow from travel stage to claims stage\n- **Reference Roles**: Creates appropriate expense references with 'report' and 'claim' roles\n\n## Automatic Expense Synchronization\nWhen linking travel to claims:\n- **Source Expenses**: All expenses from travel report are identified\n- **Reference Creation**: Expense references created in claims document\n- **Role Assignment**: Travel expenses get 'report' role, claims get 'claim' role\n- **Data Consistency**: Maintains single source of truth for expense data\n\n## Workflow Impact\n- **Stage Progression**: Workflow advances from 出張 (Travel) to 経費 (Claims)\n- **Progress Update**: Workflow completion percentage updated\n- **Document Status**: Both documents updated with relationship information\n- **Audit Trail**: Complete logging of linking operation and expense synchronization\n\n## Validation Rules\n- **Document Types**: Travel document must be 'travel' type, claims must be 'claims' type\n- **User Ownership**: User must own both documents\n- **Document Status**: Documents must be in appropriate status for linking\n- **Existing Links**: Prevents duplicate relationships between same documents\n\n## Use Cases\n- **Workflow Initiation**: Start formal reimbursement process from travel report\n- **Expense Consolidation**: Combine travel expenses into formal claims\n- **Process Automation**: Automated workflow progression and data synchronization\n- **Audit Compliance**: Maintain proper documentation chain for reimbursements\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "link_travel_to_claims": {
                  "summary": "Link travel report to claims document",
                  "value": {
                    "claims_document_id": "456e7890-f12a-34b5-c678-901234567890",
                    "travel_document_id": "123e4567-e89b-12d3-a456-426614174000"
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/LinkTravelToClaimsRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DocumentLinkResponse"
                }
              }
            },
            "description": "Travel report linked to claims document successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Invalid document IDs or documents already linked",
                      "type": "string"
                    },
                    "fieldErrors": {
                      "additionalProperties": {
                        "items": {
                          "type": "string"
                        },
                        "type": "array"
                      },
                      "example": {
                        "travel_document_id": [
                          "Travel document ID must be a valid UUID"
                        ]
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid request or validation errors"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Access denied to one or both documents",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Access denied - user does not own one or both documents"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Travel report or claims document not found",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "One or both documents not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Link travel report to claims document",
        "tags": [
          "Reimbursement Workflow"
        ]
      }
    },
    "/reimbursement/sync-expense": {
      "post": {
        "description": "Synchronize a specific expense across all linked documents in the reimbursement workflow.\n\n## Expense Synchronization\nMaintains data consistency across linked workflow documents:\n- **Cross-Document Sync**: Expense appears in all linked documents with appropriate roles\n- **Role-Based References**: Different reference roles (report, claim, payment) for each document type\n- **Data Consistency**: Single source of truth maintained across workflow\n- **Automatic Updates**: Changes propagated to all linked documents\n\n## Reference Role Assignment\n- **Report Role**: Expenses in travel reports get 'report' role\n- **Claim Role**: Expenses in claims documents get 'claim' role  \n- **Payment Role**: Expenses in payment documents get 'payment' role\n- **Context Awareness**: Role determines how expense is displayed and processed\n\n## Synchronization Scope\nSyncs expense to:\n- **Linked Travel Reports**: If claims document is linked to travel report\n- **Current Claims Document**: Source document containing the expense\n- **Linked Payment Documents**: If claims document is linked to payment document\n- **Future Links**: Automatic sync when new documents are linked\n\n## Data Integrity\n- **Consistency Checks**: Validates expense data across all references\n- **Conflict Resolution**: Handles data conflicts between document types\n- **Audit Trail**: Complete tracking of synchronization operations\n- **Error Recovery**: Rollback capabilities for failed synchronizations\n\n## Use Cases\n- **Manual Sync**: Sync specific expenses after manual entry or editing\n- **Data Correction**: Propagate expense corrections across workflow\n- **Workflow Updates**: Ensure consistency when documents are modified\n- **Integration**: Sync expenses from external systems or imports\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "sync_expense": {
                  "summary": "Sync expense across linked documents",
                  "value": {
                    "claims_document_id": "456e7890-f12a-34b5-c678-901234567890",
                    "expense_id": "exp12345-6789-abcd-efgh-ijklmnopqrst"
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/SyncExpenseRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExpenseSyncResponse"
                }
              }
            },
            "description": "Expense synchronized successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Claims document or expense not found",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Claims document or expense not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Sync expense to linked reimbursement documents",
        "tags": [
          "Reimbursement Workflow"
        ]
      }
    },
    "/reimbursement/unlinked": {
      "get": {
        "description": "Retrieve documents that are not yet linked in any reimbursement workflow, filtered by document type.\n\nFor `claims`, a claim the settlement paid rule says is paid (payout group, salary attachment or bank link — the same rule as `/reimbursement-settlement/outstanding`) is left out and counted in `paidDocuments` (BL-762). Amounts sum live expense lines only.\n\n## Unlinked Document Discovery\nFind documents available for workflow linking:\n- **Type Filtering**: Filter by document type (travel, claims, payment)\n- **Workflow Status**: Only documents not currently in workflows\n- **User Scope**: Only documents owned by authenticated user\n- **Linking Readiness**: Documents ready for workflow integration\n\n## Document Types\n- **Travel Documents**: Travel reports available for linking to claims\n- **Claims Documents**: Claims documents available for linking (to travel or payment)\n- **Payment Documents**: Payment documents available for linking to claims\n- **Status Filtering**: Only documents in appropriate status for linking\n\n## Use Cases\n- **Workflow Creation**: Find documents to start new workflows\n- **Document Discovery**: Browse available documents for linking\n- **Workflow Planning**: Identify documents ready for workflow integration\n- **User Interface**: Populate dropdown lists for document selection\n\n## Query Parameters\n- **document_type**: Filter by specific document type\n- **exclude_document_id**: Exclude specific document from results\n- **status**: Filter by document status (draft, published, etc.)\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Filter by document type",
            "example": "claims",
            "in": "query",
            "name": "document_type",
            "required": false,
            "schema": {
              "enum": [
                "travel",
                "claims",
                "payment"
              ],
              "type": "string"
            }
          },
          {
            "description": "Exclude specific document ID from results",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "in": "query",
            "name": "exclude_document_id",
            "required": false,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AvailableDocumentsResponse"
                }
              }
            },
            "description": "Unlinked documents retrieved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get unlinked documents by type",
        "tags": [
          "Reimbursement Workflow"
        ]
      }
    },
    "/reimbursement/{document_id}/dock": {
      "get": {
        "description": "Retrieve reimbursement workflow data optimized for frontend dock component display.\n\n## Dock Component Data\nReturns workflow information formatted for UI dock components:\n- **Compact Format**: Essential workflow information for sidebar display\n- **Quick Actions**: Available workflow operations and next steps\n- **Status Indicators**: Visual workflow stage and progress indicators\n- **Navigation Data**: Links to related documents and operations\n\n## Frontend Integration\nOptimized for:\n- **Sidebar Docks**: Compact workflow information display\n- **Quick Access**: Fast workflow navigation and operations\n- **Status Display**: Visual workflow progress and stage indicators\n- **Action Buttons**: Context-aware workflow operation buttons\n\n## Data Format\nStructured for frontend consumption:\n- **Minimal Payload**: Essential data only for performance\n- **UI-Ready**: Pre-formatted data for direct display\n- **Action Context**: Available operations based on workflow state\n- **Navigation**: Direct links to workflow documents and operations\n\n## Use Cases\n- **Sidebar Components**: Workflow information in application sidebars\n- **Quick Navigation**: Fast access to workflow documents and operations\n- **Status Monitoring**: Real-time workflow progress display\n- **Mobile Interfaces**: Compact workflow information for mobile apps\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the document to get dock data for",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "progress": {
                          "example": 65,
                          "type": "number"
                        },
                        "quickActions": {
                          "example": [
                            "link_to_payment",
                            "sync_expenses"
                          ],
                          "items": {
                            "type": "string"
                          },
                          "type": "array"
                        },
                        "relatedDocuments": {
                          "example": 3,
                          "type": "integer"
                        },
                        "workflowStage": {
                          "example": "経費",
                          "type": "string"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Dock data retrieved successfully",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Reimbursement dock data retrieved successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Document ID must be a valid UUID",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid document ID format"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get reimbursement dock data",
        "tags": [
          "Reimbursement Workflow"
        ]
      }
    },
    "/reimbursement/{document_id}/summary": {
      "get": {
        "description": "Retrieve comprehensive workflow summary for a reimbursement document including all linked documents and progress.\n\n## Workflow Summary Overview\nReturns complete reimbursement workflow information:\n- **Travel Report**: Original business trip documentation (if linked)\n- **Claims Documents**: Expense claim documents in the workflow\n- **Payment Documents**: Payment processing documents (if linked)\n- **Workflow Stage**: Current stage in Japanese business process\n- **Progress Tracking**: Completion percentage and workflow metrics\n\n## Japanese Reimbursement Workflow (出張経費精算フロー)\nStandard Japanese business expense reimbursement process:\n1. **出張 (Travel)**: Business trip and travel report creation\n2. **経費 (Expenses)**: Expense claims and documentation\n3. **支払 (Payment)**: Payment processing and approval\n4. **アーカイブ (Archive)**: Completed workflow archival\n\n## Workflow Stages\n- **出張 (Travel)**: Travel report stage with trip documentation\n- **経費 (Expenses)**: Claims processing and expense validation\n- **支払 (Payment)**: Payment approval and processing stage\n- **アーカイブ (Archive)**: Completed and archived workflow\n\n## Document Relationships\n- **Travel → Claims**: Travel reports linked to expense claims\n- **Claims → Payment**: Claims documents linked to payment processing\n- **Cross-References**: Expense synchronization across linked documents\n- **Audit Trail**: Complete relationship tracking and history\n\n## Progress Calculation\nWorkflow progress based on:\n- **Document Completion**: Status of individual documents\n- **Linking Status**: Relationships between workflow documents\n- **Expense Validation**: Completeness of expense data\n- **Approval Status**: Document approval and processing state\n\n## Use Cases\n- **Dashboard Views**: Display workflow status and progress\n- **Process Monitoring**: Track reimbursement workflow completion\n- **Audit Reviews**: Comprehensive workflow documentation\n- **User Interfaces**: Workflow visualization and navigation\n- **Reporting**: Workflow analytics and completion metrics\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the document to get workflow summary for",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ReimbursementWorkflowSummaryResponse"
                }
              }
            },
            "description": "Reimbursement workflow summary retrieved successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Document ID must be a valid UUID",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid document ID format"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Document not found or access denied",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Document not found or access denied"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get reimbursement workflow summary",
        "tags": [
          "Reimbursement Workflow"
        ]
      }
    },
    "/reimbursement/{source_document_id}/available-for-linking": {
      "get": {
        "description": "Retrieve documents that can be linked to a specific source document based on workflow rules.\n\n## Linking Compatibility\nFind documents compatible for workflow linking:\n- **Workflow Rules**: Only compatible document types for linking\n- **Status Validation**: Documents in appropriate status for linking\n- **Existing Links**: Excludes documents already linked to source\n- **User Permissions**: Only documents accessible to authenticated user\n\n## Link Type Validation\n- **Travel to Claims**: Travel documents can link to claims documents\n- **Claims to Payment**: Claims documents can link to payment documents\n- **Type Enforcement**: Prevents invalid workflow combinations\n- **Direction Rules**: Maintains proper workflow direction and hierarchy\n\n## Compatibility Checking\n- **Document Status**: Target documents must be in linkable status\n- **User Ownership**: User must own both source and target documents\n- **Workflow State**: Documents must not conflict with existing workflows\n- **Business Rules**: Follows Japanese reimbursement workflow patterns\n\n## Query Parameters\n- **link_type**: Specify the type of linking (travel_to_claims, claims_to_payment)\n- **status**: Filter target documents by status\n- **limit**: Limit number of results returned\n\n## Use Cases\n- **Workflow Building**: Find compatible documents for workflow creation\n- **User Interface**: Populate selection lists with valid options\n- **Validation**: Verify linking compatibility before attempting operations\n- **Discovery**: Help users find documents ready for linking\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the source document to find linking targets for",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "in": "path",
            "name": "source_document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Type of linking to find compatible documents for",
            "example": "travel_to_claims",
            "in": "query",
            "name": "link_type",
            "required": false,
            "schema": {
              "enum": [
                "travel_to_claims",
                "claims_to_payment"
              ],
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AvailableDocumentsResponse"
                }
              }
            },
            "description": "Available documents for linking retrieved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Source document not found or access denied",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Source document not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get available documents for linking",
        "tags": [
          "Reimbursement Workflow"
        ]
      }
    },
    "/remark-dictionary": {
      "get": {
        "description": "Get all remark dictionary entries for the authenticated user with intelligent sorting.\n\n## Remark Dictionary (摘要辞書)\nComprehensive remark management with:\n- **Description Library**: Complete collection of user's accounting descriptions\n- **Intelligent Sorting**: Sorted by usage frequency and alphabetical order\n- **Usage Analytics**: Remarks sorted by usage count for quick access to frequently used descriptions\n- **Account Integration**: Optional account linking for automatic categorization\n- **Japanese Support**: Full support for Japanese text with reading (フリガナ) assistance\n\n## Sorting Logic\nRemarks are sorted in the following priority order:\n1. **Usage Frequency**: Most frequently used remarks appear first\n2. **Alphabetical Order**: Within same usage count, sorted alphabetically for consistency\n\n## Remark Information\nEach remark includes:\n- **Text Content**: The actual remark text used in journal entries\n- **Reading Support**: Optional フリガナ (reading) for Japanese text input assistance\n- **Account Linking**: Optional account association for automatic categorization\n- **Category Linking**: Optional expense category association\n- **Usage Statistics**: Usage count and last used timestamp for analytics\n- **Status Information**: Active/inactive status and timestamps\n\n## Use Cases\n- **Remark Selection**: Browse and select remarks for journal entry descriptions\n- **Usage Analysis**: Analyze remark usage patterns for workflow optimization\n- **Remark Management**: Review remark library for maintenance and updates\n- **Workflow Optimization**: Identify most frequently used remarks for quick access\n- **Categorization**: Review account and category associations for automation\n\n## Filtering Options\n- **Active Only (default)**: Show only active remarks for normal operations\n- **Include Inactive**: Include inactive remarks for comprehensive management\n\n## Account Integration\n- **Optional Linking**: Remarks can be optionally linked to chart of accounts\n- **Categorization**: Support for expense category associations\n- **Automation**: Linked accounts enable automatic account selection in journal entries\n\nBearer token authentication required.",
        "parameters": [
          {
            "description": "Include inactive remarks (default: false)",
            "example": false,
            "in": "query",
            "name": "include_inactive",
            "required": false,
            "schema": {
              "default": false,
              "type": "boolean"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RemarkListResponse"
                }
              }
            },
            "description": "Remark dictionary retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List remark dictionary entries (摘要辞書一覧)",
        "tags": [
          "Remark Dictionary"
        ]
      },
      "post": {
        "description": "Create a new remark dictionary entry for automated accounting description management.\n\n## Remark Creation\nComprehensive remark setup with:\n- **Text Content**: Primary remark text for journal entry descriptions\n- **Reading Support**: Optional フリガナ (reading) for Japanese text input assistance\n- **Account Linking**: Optional account association for automatic categorization\n- **Category Association**: Optional expense category linking for workflow automation\n- **Usage Tracking**: Automatic usage count initialization for analytics\n\n## Validation Rules\n- **Duplicate Prevention**: Ensures remark text uniqueness per user\n- **Account Validation**: Validates linked account existence if provided\n- **Text Requirements**: Remark text is required and must be meaningful\n- **User Isolation**: Remarks are isolated by user to prevent conflicts\n\n## Japanese Text Support\n- **Native Japanese**: Full support for Japanese text in remark content\n- **Reading (フリガナ)**: Optional reading field for pronunciation assistance\n- **Search Integration**: Reading field integrated into auto-suggest functionality\n- **Input Assistance**: Supports both text and reading-based input methods\n\n## Account Integration Features\n- **Optional Linking**: Account linking is optional for flexible usage\n- **Chart Integration**: Integrates with chart of accounts for proper classification\n- **Automatic Selection**: Linked accounts enable automatic account selection in journal entries\n- **Category Support**: Supports expense category associations for enhanced automation\n\n## Usage Analytics\n- **Usage Tracking**: Automatic usage count initialization for popularity analytics\n- **Sorting Impact**: Usage data influences sorting order for optimal user experience\n- **Workflow Optimization**: Usage analytics help optimize remark organization\n\n## Use Cases\n- **Standard Descriptions**: Create standard descriptions for common transactions\n- **Automation Setup**: Set up remarks with account linking for automated workflows\n- **Japanese Support**: Create Japanese remarks with reading assistance\n- **Categorization**: Associate remarks with accounts and categories for organization\n- **Efficiency Improvement**: Build remark library for improved accounting efficiency\n\nBearer token authentication required.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateRemarkRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RemarkCreateResponse"
                }
              }
            },
            "description": "Remark created successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "ACCOUNT_NOT_FOUND",
                      "type": "string"
                    },
                    "error": {
                      "example": "Linked account not found",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Linked account not found"
          },
          "409": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "DUPLICATE_REMARK",
                      "type": "string"
                    },
                    "error": {
                      "example": "Remark already exists",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Remark already exists"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create remark dictionary entry (摘要辞書作成)",
        "tags": [
          "Remark Dictionary"
        ]
      }
    },
    "/remark-dictionary/suggest": {
      "get": {
        "description": "Get auto-suggestions for remark entries based on query input with intelligent search.\n\n## Auto-Suggest Functionality\nIntelligent suggestion system with:\n- **Prefix Search**: Primary search by remark text prefix for exact matches\n- **Reading Search**: Search by フリガナ (reading) prefix for Japanese input assistance\n- **Contains Search**: Fallback search for partial matches within remark text\n- **Usage-Based Ranking**: Results sorted by usage frequency for optimal relevance\n- **Configurable Limit**: Adjustable result limit for performance optimization\n\n## Search Strategy\nMulti-layered search approach:\n1. **Prefix Match**: Exact prefix matching on remark text (highest priority)\n2. **Reading Prefix**: Prefix matching on フリガナ reading field\n3. **Contains Match**: Partial text matching within remark content\n4. **Usage Ranking**: All results sorted by usage count for relevance\n5. **Alphabetical Fallback**: Secondary alphabetical sorting for consistency\n\n## Search Features\n- **Case Insensitive**: Search is case-insensitive for better usability\n- **Japanese Support**: Full support for Japanese text and reading search\n- **Performance Optimized**: Efficient database queries with proper indexing\n- **Relevance Ranking**: Results ranked by usage frequency and relevance\n- **Active Only**: Only searches active remarks for clean results\n\n## Use Cases\n- **Real-time Input**: Provide real-time suggestions during journal entry creation\n- **Efficiency Improvement**: Speed up data entry with intelligent suggestions\n- **Discovery**: Help users discover existing remarks to avoid duplicates\n- **Japanese Input**: Assist with Japanese text input using reading search\n- **Workflow Optimization**: Promote frequently used remarks for consistency\n\n## Query Requirements\n- **Minimum Length**: Query must be at least 1 character long\n- **Empty Query**: Returns empty array for empty or missing queries\n- **Performance**: Optimized for real-time usage with fast response times\n\n## Response Format\n- **Suggestion Data**: Each suggestion includes ID, text, reading, and usage count\n- **Account Information**: Includes linked account information if available\n- **Usage Context**: Usage count provided for relevance assessment\n- **Sorted Results**: Results pre-sorted by relevance and usage frequency\n\nBearer token authentication required.",
        "parameters": [
          {
            "description": "Search query for remark suggestions",
            "example": "電車",
            "in": "query",
            "name": "q",
            "required": true,
            "schema": {
              "minLength": 1,
              "type": "string"
            }
          },
          {
            "description": "Maximum number of suggestions to return (default: 10)",
            "example": 10,
            "in": "query",
            "name": "limit",
            "required": false,
            "schema": {
              "default": 10,
              "maximum": 50,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RemarkSuggestionsResponse"
                }
              }
            },
            "description": "Suggestions retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Auto-suggest remark entries (摘要辞書自動補完)",
        "tags": [
          "Remark Dictionary"
        ]
      }
    },
    "/remark-dictionary/{id}": {
      "delete": {
        "description": "Delete a remark dictionary entry using soft delete to preserve audit trail.\n\n## Soft Delete Implementation\nSafe remark removal with:\n- **Audit Trail Preservation**: Remark data preserved for audit purposes\n- **Status Deactivation**: Remark marked as inactive rather than physically deleted\n- **Usage History**: Usage statistics and history preserved\n- **Reversible Operation**: Remark can be reactivated if needed\n- **Search Exclusion**: Inactive remarks excluded from suggestions and normal lists\n\n## Delete Process\n1. **Ownership Validation**: Verify remark belongs to authenticated user\n2. **Status Update**: Mark remark as inactive (is_active = false)\n3. **Timestamp Update**: Update modification timestamp\n4. **Audit Logging**: Log deletion operation for audit trail\n5. **Search Impact**: Remove from active search results\n\n## Impact on Operations\n- **Remark Lists**: Deleted remarks excluded from default lists\n- **Auto-Suggest**: Inactive remarks excluded from suggestion results\n- **Usage Statistics**: Historical usage data preserved\n- **Journal Entries**: Existing journal entries using remark unaffected\n\n## Use Cases\n- **Remark Cleanup**: Remove unused or obsolete remarks\n- **Library Organization**: Clean up remark library for better management\n- **Workflow Optimization**: Remove remarks that are no longer relevant\n- **Data Maintenance**: Regular maintenance of remark dictionary\n\n## Recovery Options\n- **Reactivation**: Remarks can be reactivated by updating is_active status\n- **Data Preservation**: All remark data preserved for potential recovery\n- **Audit Trail**: Complete history of remark lifecycle maintained\n\nBearer token authentication required.",
        "parameters": [
          {
            "description": "Remark ID",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RemarkDeleteResponse"
                }
              }
            },
            "description": "Remark deleted successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Delete remark dictionary entry (soft delete)",
        "tags": [
          "Remark Dictionary"
        ]
      },
      "get": {
        "description": "Get detailed information about a specific remark dictionary entry.\n\n## Remark Details\nComprehensive remark information with:\n- **Complete Remark Data**: All remark fields including metadata\n- **Account Information**: Detailed linked account information if associated\n- **Usage Statistics**: Current usage count and last used timestamp\n- **Reading Support**: フリガナ (reading) information for Japanese text\n- **Status Information**: Active status and timestamp information\n\n## Account Integration\n- **Account Details**: Full account information including code, name, and type\n- **Chart Integration**: Integration with chart of accounts for proper classification\n- **Relationship Integrity**: Maintains proper account relationship references\n- **Access Validation**: Ensures remark belongs to authenticated user\n\n## Use Cases\n- **Remark Review**: Review remark configuration before use or editing\n- **Usage Analysis**: Analyze remark usage statistics and patterns\n- **Account Verification**: Verify account associations and relationships\n- **Data Retrieval**: Retrieve complete remark data for application integration\n- **Audit Trail**: Access complete remark information for audit purposes\n\n## Security\n- **User Isolation**: Remarks are isolated by user ID\n- **Access Control**: Only remark owner can access remark details\n- **Authentication Required**: Bearer token authentication required\n\nBearer token authentication required.",
        "parameters": [
          {
            "description": "Remark ID",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RemarkResponse"
                }
              }
            },
            "description": "Remark retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get remark dictionary entry by ID",
        "tags": [
          "Remark Dictionary"
        ]
      },
      "put": {
        "description": "Update an existing remark dictionary entry with new configuration.\n\n## Remark Updates\nComprehensive remark modification with:\n- **Flexible Updates**: Update any remark field independently\n- **Text Modification**: Change remark text with duplicate validation\n- **Reading Updates**: Modify フリガナ (reading) for Japanese text assistance\n- **Account Changes**: Modify account associations with validation\n- **Status Management**: Activate or deactivate remarks\n\n## Validation Rules\n- **Duplicate Prevention**: Ensures remark text uniqueness when modified\n- **Account Validation**: Validates new account associations if changed\n- **User Ownership**: Validates remark belongs to authenticated user\n- **Text Requirements**: Ensures meaningful remark text content\n\n## Update Features\n- **Partial Updates**: Only specified fields are updated\n- **Timestamp Management**: Automatic updated_at timestamp management\n- **Account Integration**: Real-time account validation and relationship updates\n- **Usage Preservation**: Usage statistics preserved during updates\n\n## Use Cases\n- **Content Updates**: Update remark text as business needs change\n- **Account Changes**: Update account associations when chart of accounts changes\n- **Reading Updates**: Modify フリガナ for improved Japanese text support\n- **Status Management**: Activate or deactivate remarks based on usage\n- **Configuration Tuning**: Fine-tune account and category associations\n\n## Security\n- **User Isolation**: Only remark owner can update remarks\n- **Access Control**: Authentication and ownership validation required\n- **Data Integrity**: Comprehensive validation prevents data corruption\n\nBearer token authentication required.",
        "parameters": [
          {
            "description": "Remark ID",
            "example": "123e4567-e89b-12d3-a456-426614174000",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateRemarkRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RemarkUpdateResponse"
                }
              }
            },
            "description": "Remark updated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "DUPLICATE_REMARK",
                      "type": "string"
                    },
                    "error": {
                      "example": "Remark with this text already exists",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Remark with this text already exists"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update remark dictionary entry",
        "tags": [
          "Remark Dictionary"
        ]
      }
    },
    "/reminders": {
      "get": {
        "description": "Retrieve current active reminders for the authenticated user with urgency prioritization.\n\n## Current Reminders (現在のリマインダー)\nComprehensive reminder management with:\n- **Urgency Prioritization**: Reminders sorted by urgency and due date proximity\n- **Japanese Business Calendar**: Integration with Japanese fiscal year and business calendar\n- **Tax Deadline Tracking**: Automatic tracking of Japanese tax and compliance deadlines\n- **Custom Reminder Support**: User-created reminders alongside system-generated ones\n- **Status Management**: Track completion status and overdue reminders\n- **Multi-Type Support**: Support for various reminder types (tax, insurance, custom)\n\n## Reminder Types\n\n### Monthly/Fiscal Year Dependent\n- **Reimbursement (経費精算)**: Monthly reimbursement processing reminders\n- **Expense Payment (経費支払)**: Expense payment deadline reminders\n- **Invoice (請求書)**: Invoice generation and submission reminders\n- **Corporate Tax (法人税)**: Corporate tax filing deadline reminders (fiscal year dependent)\n- **Year-End Adjustment (年末調整)**: Year-end tax adjustment reminders\n- **Consumption Tax (消費税)**: Consumption tax filing reminders (fiscal year dependent)\n- **Labor Insurance (労働保険)**: Labor insurance payment reminders (June/July)\n- **Social Insurance (社会保険)**: Social insurance payment reminders (July)\n- **Custom (カスタム)**: User-defined custom reminders\n\n### Fixed Calendar-Year Statutory Deadlines (January 31st)\nThese are universal statutory deadlines that apply to ALL Japanese businesses:\n- **Legal Records Summary (法定調書合計表)**: e-Tax submission deadline\n- **Withholding Tax Slip (源泉徴収票)**: e-Tax submission to tax office and employees\n- **Salary Payment Report (給与支払報告書)**: eLTAX submission to municipalities\n- **Depreciable Assets (償却資産申告)**: eLTAX fixed asset tax declaration\n\n## Urgency Levels\n- **Critical**: Due today or overdue (immediate attention required)\n- **High**: Due within 3 days (urgent attention needed)\n- **Medium**: Due within 7 days (attention needed soon)\n- **Low**: Due within 30 days (advance notice)\n\n## Use Cases\n- **Daily Dashboard**: Daily overview of upcoming deadlines and tasks\n- **Compliance Management**: Track Japanese business compliance requirements\n- **Tax Planning**: Monitor tax filing deadlines and preparation requirements\n- **Business Operations**: Manage routine business operations and deadlines\n- **Custom Scheduling**: Track user-specific deadlines and appointments\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "current_reminders": {
                    "summary": "Current reminders with various urgency levels",
                    "value": {
                      "data": [
                        {
                          "created_at": "2024-01-01T00:00:00.000Z",
                          "day": 17,
                          "days_until_due": 2,
                          "deleted_at": null,
                          "id": "123e4567-e89b-12d3-a456-426614174000",
                          "is_deleted": false,
                          "is_done": false,
                          "month": 4,
                          "next_due_date": "2024-04-17",
                          "reminder_cycle": 1,
                          "reminder_type": 3,
                          "title": "法人税申告書提出期限",
                          "updated_at": "2024-01-15T10:30:00.000Z",
                          "urgency_level": "high",
                          "user_id": "abc12345-def6-7890-ghij-klmnopqrstuv",
                          "week_day": null,
                          "year": null
                        },
                        {
                          "created_at": "2024-01-10T00:00:00.000Z",
                          "day": 25,
                          "days_until_due": 10,
                          "deleted_at": null,
                          "id": "456e7890-f12a-34b5-c678-901234567890",
                          "is_deleted": false,
                          "is_done": false,
                          "month": null,
                          "next_due_date": "2024-04-25",
                          "reminder_cycle": 0,
                          "reminder_type": 8,
                          "title": "Monthly office rent payment",
                          "updated_at": "2024-01-10T00:00:00.000Z",
                          "urgency_level": "medium",
                          "user_id": "abc12345-def6-7890-ghij-klmnopqrstuv",
                          "week_day": null,
                          "year": null
                        }
                      ],
                      "message": "Current reminders retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/RemindersListResponse"
                }
              }
            },
            "description": "Current reminders retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get current reminders",
        "tags": [
          "Reminders"
        ]
      }
    },
    "/reminders/configs": {
      "get": {
        "description": "Retrieve reminder configuration settings for the authenticated user.\n\n## Reminder Configuration (リマインダー設定)\nComprehensive configuration management with:\n- **Japanese Business Standards**: Pre-configured with Japanese business deadline standards\n- **Flexible Scheduling**: Customizable day and month settings for each reminder type\n- **Active/Inactive Control**: Individual enable/disable control for each reminder type\n- **Default Settings**: Sensible defaults based on Japanese business practices\n- **Fiscal Year Integration**: Integration with Japanese fiscal year calendar\n- **Compliance Support**: Configuration aligned with Japanese compliance requirements\n\n## Configuration Types\n- **Monthly Reminders**: Reimbursement, expense payment, and invoice reminders\n- **Annual Tax Reminders**: Corporate tax, consumption tax, and year-end adjustments\n- **Insurance Reminders**: Labor and social insurance payment deadlines\n- **Custom Settings**: User-specific timing preferences for each reminder type\n\n## Default Settings (Japanese Business Standards)\n\n### Monthly Reminders\n- **Reimbursement**: 25th of each month\n- **Expense Payment**: 30th of each month (month-end)\n- **Invoice**: 25th of each month\n\n### Fiscal Year Dependent\n- **Corporate Tax**: April 17th (Japanese fiscal year end + 2.5 months)\n- **Consumption Tax**: April 17th (quarterly/annual filing)\n\n### Fixed Annual Deadlines\n- **Year-End Adjustment**: January 31st\n- **Labor Insurance**: July 10th (annual payment)\n- **Social Insurance**: July 10th (annual adjustment)\n\n### Statutory Deadlines (January 31st - Active by Default)\n- **Legal Records Summary (法定調書合計表)**: January 31st (e-Tax)\n- **Withholding Tax Slip (源泉徴収票)**: January 31st (e-Tax)\n- **Salary Payment Report (給与支払報告書)**: January 31st (eLTAX)\n- **Depreciable Assets (償却資産申告)**: January 31st (eLTAX)\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "default_config": {
                    "summary": "Default Japanese business reminder configuration",
                    "value": {
                      "data": {
                        "consumption_tax_active": true,
                        "consumption_tax_day": 17,
                        "consumption_tax_month": 4,
                        "corporate_tax_active": true,
                        "corporate_tax_day": 17,
                        "corporate_tax_month": 4,
                        "created_at": "2024-01-01T00:00:00.000Z",
                        "expense_payment_active": true,
                        "expense_payment_day": 30,
                        "id": "123e4567-e89b-12d3-a456-426614174000",
                        "invoice_active": true,
                        "invoice_day": 25,
                        "labor_insurance_active": true,
                        "labor_insurance_day": 10,
                        "labor_insurance_month": 7,
                        "reimbursement_active": true,
                        "reimbursement_day": 25,
                        "social_insurance_active": true,
                        "social_insurance_day": 10,
                        "social_insurance_month": 7,
                        "updated_at": "2024-01-15T10:30:00.000Z",
                        "user_id": "abc12345-def6-7890-ghij-klmnopqrstuv",
                        "year_end_adjustment_active": true,
                        "year_end_adjustment_day": 31,
                        "year_end_adjustment_month": 1
                      },
                      "message": "Reminder configs retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/ReminderConfigResponse"
                }
              }
            },
            "description": "Reminder configurations retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Reminder configuration not found for user",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Reminder configuration not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get reminder configurations",
        "tags": [
          "Reminders"
        ]
      },
      "put": {
        "description": "Update reminder configuration settings for the authenticated user.\n\n## Configuration Update (設定更新)\nComprehensive configuration management with:\n- **Partial Updates**: Update only the settings you want to change\n- **Validation**: Comprehensive validation of day/month combinations\n- **Japanese Calendar**: Validation against Japanese business calendar\n- **Future Reminder Updates**: Automatic update of future reminder schedules\n- **Audit Trail**: Complete audit trail of configuration changes\n- **Default Preservation**: Preserve existing settings for unchanged fields\n\n## Update Validation\n- **Day Validation**: Ensure days are valid for the specified months\n- **Month Validation**: Validate months against Japanese fiscal year\n- **Business Logic**: Ensure settings align with Japanese business practices\n- **Dependency Checking**: Validate interdependent settings (day/month pairs)\n- **Range Validation**: Ensure all values are within acceptable ranges\n\n## Impact of Changes\n- **Future Reminders**: Updates automatically apply to future reminder schedules\n- **Active Reminders**: Existing active reminders remain unchanged\n- **Notification Schedule**: Notification schedules updated based on new settings\n- **Calendar Integration**: Integration with Japanese business calendar updated\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "full_update": {
                  "summary": "Complete configuration update",
                  "value": {
                    "consumption_tax_active": true,
                    "consumption_tax_day": 17,
                    "consumption_tax_month": 4,
                    "corporate_tax_active": true,
                    "corporate_tax_day": 17,
                    "corporate_tax_month": 4,
                    "expense_payment_active": true,
                    "expense_payment_day": 30,
                    "invoice_active": true,
                    "invoice_day": 25,
                    "labor_insurance_active": true,
                    "labor_insurance_day": 10,
                    "labor_insurance_month": 7,
                    "reimbursement_active": true,
                    "reimbursement_day": 25,
                    "social_insurance_active": true,
                    "social_insurance_day": 10,
                    "social_insurance_month": 7,
                    "year_end_adjustment_active": true,
                    "year_end_adjustment_day": 31,
                    "year_end_adjustment_month": 1
                  }
                },
                "partial_update": {
                  "summary": "Partial configuration update",
                  "value": {
                    "corporate_tax_active": false,
                    "reimbursement_active": true,
                    "reimbursement_day": 20
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/UpdateReminderConfigRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ReminderConfigResponse"
                }
              }
            },
            "description": "Reminder configuration updated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Reminder configuration not found for user",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Reminder configuration not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update reminder configuration",
        "tags": [
          "Reminders"
        ]
      }
    },
    "/reminders/custom": {
      "get": {
        "description": "Retrieve all custom reminders created by the authenticated user.\n\n## Custom Reminders (カスタムリマインダー)\nUser-created reminder management with:\n- **Flexible Scheduling**: Support for monthly, yearly, and weekly cycles\n- **Custom Titles**: User-defined reminder titles and descriptions\n- **Multiple Cycles**: Support for various reminder frequencies\n- **Status Tracking**: Track completion and deletion status\n- **Priority Sorting**: Sorted by due date and urgency for optimal workflow\n- **Japanese Support**: Full support for Japanese titles and descriptions\n\n## Reminder Cycles\n- **Monthly**: Recurring monthly reminders on specified day\n- **Yearly**: Annual reminders on specified day and month\n- **Weekly**: Weekly reminders on specified day of week\n\n## Use Cases\n- **Personal Deadlines**: Track personal business deadlines and appointments\n- **Custom Business Tasks**: Create reminders for business-specific tasks\n- **Project Milestones**: Track project deadlines and milestones\n- **Recurring Tasks**: Set up recurring tasks and maintenance reminders\n- **Special Events**: Create reminders for special events and occasions\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RemindersListResponse"
                }
              }
            },
            "description": "Custom reminders retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get custom reminders",
        "tags": [
          "Reminders"
        ]
      },
      "post": {
        "description": "Create a new custom reminder with flexible scheduling options.\n\n## Custom Reminder Creation (カスタムリマインダー作成)\nFlexible reminder creation with:\n- **Multiple Cycles**: Support for monthly, yearly, and weekly reminder cycles\n- **Flexible Scheduling**: Customize day, month, year, and week day settings\n- **Validation**: Comprehensive validation of scheduling parameters\n- **Japanese Support**: Full support for Japanese titles and descriptions\n- **Automatic Scheduling**: Automatic calculation of next due dates\n- **Integration**: Integration with existing reminder system and notifications\n\n## Scheduling Options\n- **Monthly Reminders**: Specify day of month (1-31)\n- **Yearly Reminders**: Specify day and month (requires both)\n- **Weekly Reminders**: Specify day of week (0=Sunday, 6=Saturday)\n- **One-Time Reminders**: Specify specific year for one-time events\n\n## Validation Rules\n- **Required Fields**: Title, reminder cycle, reminder type, and day are required\n- **Conditional Fields**: Month required for yearly cycle, week_day for weekly cycle\n- **Range Validation**: All numeric fields validated within acceptable ranges\n- **Date Validation**: Ensure valid date combinations (e.g., February 30th not allowed)\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "monthly_reminder": {
                  "summary": "Monthly recurring reminder",
                  "value": {
                    "day": 25,
                    "reminder_cycle": 0,
                    "reminder_type": 8,
                    "title": "Monthly office rent payment"
                  }
                },
                "weekly_reminder": {
                  "summary": "Weekly recurring reminder",
                  "value": {
                    "day": 1,
                    "reminder_cycle": 2,
                    "reminder_type": 8,
                    "title": "Weekly team meeting preparation",
                    "week_day": 1
                  }
                },
                "yearly_reminder": {
                  "summary": "Annual reminder with specific month",
                  "value": {
                    "day": 15,
                    "month": 3,
                    "reminder_cycle": 1,
                    "reminder_type": 8,
                    "title": "Annual insurance renewal"
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/CreateReminderRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ReminderResponse"
                }
              }
            },
            "description": "Custom reminder created successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create custom reminder",
        "tags": [
          "Reminders"
        ]
      }
    },
    "/reminders/custom/{id}": {
      "delete": {
        "description": "Delete a custom reminder created by the authenticated user.\n\n## Custom Reminder Deletion (カスタムリマインダー削除)\nSafe reminder deletion with:\n- **Soft Deletion**: Reminders are soft-deleted to preserve audit trail\n- **User Validation**: Ensure user can only delete their own reminders\n- **Status Update**: Update deletion status and timestamp\n- **Audit Trail**: Complete audit trail of deletion actions\n- **Recovery**: Possibility of recovery through administrative functions\n\n## Deletion Process\n- **Ownership Verification**: Verify user owns the reminder before deletion\n- **Status Update**: Mark reminder as deleted with timestamp\n- **Audit Logging**: Log deletion action for audit and compliance\n- **Notification Cleanup**: Remove associated notifications and schedules\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Custom reminder ID to delete",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ReminderActionResponse"
                }
              }
            },
            "description": "Custom reminder deleted successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Cannot delete system-generated reminders",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Forbidden - Cannot delete system reminders"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Custom reminder not found",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Custom reminder not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Delete custom reminder",
        "tags": [
          "Reminders"
        ]
      }
    },
    "/reminders/enhanced": {
      "get": {
        "description": "Retrieve enhanced reminders with per-action details for statutory tasks.\n\n## Enhanced Reminders (拡張リマインダー)\nReturns reminders with additional metadata for statutory tasks:\n- **Multi-Action Support**: Statutory tasks can have multiple actions (e.g., 交付 to employees, 提出 to tax office)\n- **Per-Action Completion**: Track completion status for each action independently\n- **Recipient Information**: Shows who receives the document (税務署, 市区町村, 従業員, etc.)\n- **Submission Methods**: Shows how to submit (e-Tax, eLTAX, 手渡し, etc.)\n- **Conditional Actions**: Some actions only apply under certain conditions\n\n## Example: 源泉徴収票 (Withholding Tax Slip)\nThis task has TWO actions:\n1. **交付 (Distribute)** → 従業員 - Required for ALL employees\n2. **提出 (Submit)** → 所轄税務署 - Only if 役員 >¥150万 or 従業員 >¥500万\n\n## Overall Completion Logic\n`is_done` at the reminder level is `true` only when ALL required actions are complete.\n\n## Badge Colors by Recipient Type\n| Recipient | Color |\n|-----------|-------|\n| TAX_OFFICE | Blue |\n| MUNICIPALITY | Green |\n| EMPLOYEE | Purple |\n| PENSION_OFFICE | Teal |\n| SELF | Orange |\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "withholding_tax_slip": {
                    "summary": "源泉徴収票 with multi-action support",
                    "value": {
                      "data": [
                        {
                          "actions": [
                            {
                              "actionLabel": "交付",
                              "actionType": "DISTRIBUTE",
                              "displayOrder": 1,
                              "id": "123e4567-e89b-12d3-a456-426614174001",
                              "isDone": false,
                              "isRequired": true,
                              "method": {
                                "label": "手渡し・郵送",
                                "type": "HAND_DELIVERY"
                              },
                              "recipient": {
                                "label": "従業員",
                                "type": "EMPLOYEE"
                              }
                            },
                            {
                              "actionLabel": "提出",
                              "actionType": "SUBMIT",
                              "condition": {
                                "isMet": false,
                                "key": "HIGH_EARNER",
                                "label": "役員年収 >¥150万 または 従業員年収 >¥500万"
                              },
                              "displayOrder": 2,
                              "id": "123e4567-e89b-12d3-a456-426614174002",
                              "isDone": false,
                              "isRequired": false,
                              "method": {
                                "label": "e-Tax",
                                "type": "E_TAX"
                              },
                              "recipient": {
                                "label": "所轄税務署",
                                "type": "TAX_OFFICE"
                              }
                            }
                          ],
                          "day": 31,
                          "description": "給与所得の源泉徴収票",
                          "id": "system-withholding-tax-slip-2026",
                          "is_done": false,
                          "month": 1,
                          "reminder_cycle": 1,
                          "reminder_type": 10,
                          "shortTitle": "源泉徴収票",
                          "title": "源泉徴収票",
                          "year": 2026
                        }
                      ],
                      "message": "Enhanced reminders retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/EnhancedRemindersListResponse"
                }
              }
            },
            "description": "Enhanced reminders retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get enhanced reminders with multi-action support",
        "tags": [
          "Reminders"
        ]
      }
    },
    "/reminders/notification-preferences": {
      "get": {
        "description": "`deadlineEmail` (申告カレンダーの期限をメールで知らせる) is true unless the user turned it off. The daily reminder-notify job reads the same key: 30 / 7 / 1 days before a deadline, then overdue nudges until it is recorded as filed. `hasEmail` is false when the account has no address to mail.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "additionalProperties": false,
                      "properties": {
                        "calendarOwnedReminderTypes": {
                          "description": "ReminderType values the user's 申告カレンダー now owns (CALENDAR_OWNED_REMINDERS): the mail job skips their legacy items and 通知設定 hides their rows. The same list both use.",
                          "example": [
                            3,
                            4,
                            5,
                            6,
                            7
                          ],
                          "items": {
                            "type": "integer"
                          },
                          "type": "array"
                        },
                        "deadlineBeforeDayOptions": {
                          "description": "The days 通知設定 offers (the list the mail job accepts).",
                          "example": [
                            30,
                            14,
                            7,
                            3,
                            1
                          ],
                          "items": {
                            "type": "integer"
                          },
                          "type": "array"
                        },
                        "deadlineBeforeDays": {
                          "description": "Days before a deadline to mail, as chosen in 通知設定; null = 標準 (each deadline's own, mostly 30 / 7 / 1).",
                          "example": null,
                          "items": {
                            "enum": [
                              30,
                              14,
                              7,
                              3,
                              1
                            ],
                            "type": "integer"
                          },
                          "nullable": true,
                          "type": "array"
                        },
                        "deadlineEmail": {
                          "type": "boolean"
                        },
                        "deadlineOverdueRepeat": {
                          "description": "After the date, while unfiled: off = the day after only; weekly = the day after, then every week; biweekly (標準) = the day after, a week after, then every 2 weeks.",
                          "enum": [
                            "off",
                            "weekly",
                            "biweekly"
                          ],
                          "example": "biweekly",
                          "type": "string"
                        },
                        "deadlineStandardBeforeDays": {
                          "description": "What 標準 means, for the checkboxes when deadlineBeforeDays is null.",
                          "example": [
                            30,
                            7,
                            1
                          ],
                          "items": {
                            "type": "integer"
                          },
                          "type": "array"
                        },
                        "decisionEmail": {
                          "description": "Mail open questions 14 / 3 / 0 days before their 判断の目安日 (review_by), and once if it passed unreminded. Default true (BE ADR-0025).",
                          "type": "boolean"
                        },
                        "hasEmail": {
                          "type": "boolean"
                        },
                        "weeklyDigestEmail": {
                          "description": "The Monday 「今週のまとめ」 (this week, overdue, 判断の目安日, unrecorded 納付・控え) inside that day's one reminder mail; left out when empty. Default true (BE ADR-0025).",
                          "type": "boolean"
                        }
                      },
                      "required": [
                        "hasEmail",
                        "deadlineEmail",
                        "weeklyDigestEmail",
                        "decisionEmail",
                        "calendarOwnedReminderTypes",
                        "deadlineBeforeDays",
                        "deadlineOverdueRepeat",
                        "deadlineBeforeDayOptions",
                        "deadlineStandardBeforeDays"
                      ],
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "The switches"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "User profile not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get the mail switches in 通知設定",
        "tags": [
          "Reminders"
        ]
      },
      "patch": {
        "description": "Merges the given keys into notification_preferences; other keys are left as they are. At least one key. `deadlineBeforeDays: null` goes back to 標準.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "additionalProperties": false,
                "minProperties": 1,
                "properties": {
                  "deadlineBeforeDays": {
                    "items": {
                      "enum": [
                        30,
                        14,
                        7,
                        3,
                        1
                      ],
                      "type": "integer"
                    },
                    "maxItems": 5,
                    "nullable": true,
                    "type": "array"
                  },
                  "deadlineEmail": {
                    "type": "boolean"
                  },
                  "deadlineOverdueRepeat": {
                    "enum": [
                      "off",
                      "weekly",
                      "biweekly"
                    ],
                    "type": "string"
                  },
                  "decisionEmail": {
                    "type": "boolean"
                  },
                  "weeklyDigestEmail": {
                    "type": "boolean"
                  }
                },
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "additionalProperties": false,
                      "properties": {
                        "calendarOwnedReminderTypes": {
                          "description": "ReminderType values the user's 申告カレンダー now owns (CALENDAR_OWNED_REMINDERS): the mail job skips their legacy items and 通知設定 hides their rows. The same list both use.",
                          "example": [
                            3,
                            4,
                            5,
                            6,
                            7
                          ],
                          "items": {
                            "type": "integer"
                          },
                          "type": "array"
                        },
                        "deadlineBeforeDayOptions": {
                          "description": "The days 通知設定 offers (the list the mail job accepts).",
                          "example": [
                            30,
                            14,
                            7,
                            3,
                            1
                          ],
                          "items": {
                            "type": "integer"
                          },
                          "type": "array"
                        },
                        "deadlineBeforeDays": {
                          "description": "Days before a deadline to mail, as chosen in 通知設定; null = 標準 (each deadline's own, mostly 30 / 7 / 1).",
                          "example": null,
                          "items": {
                            "enum": [
                              30,
                              14,
                              7,
                              3,
                              1
                            ],
                            "type": "integer"
                          },
                          "nullable": true,
                          "type": "array"
                        },
                        "deadlineEmail": {
                          "type": "boolean"
                        },
                        "deadlineOverdueRepeat": {
                          "description": "After the date, while unfiled: off = the day after only; weekly = the day after, then every week; biweekly (標準) = the day after, a week after, then every 2 weeks.",
                          "enum": [
                            "off",
                            "weekly",
                            "biweekly"
                          ],
                          "example": "biweekly",
                          "type": "string"
                        },
                        "deadlineStandardBeforeDays": {
                          "description": "What 標準 means, for the checkboxes when deadlineBeforeDays is null.",
                          "example": [
                            30,
                            7,
                            1
                          ],
                          "items": {
                            "type": "integer"
                          },
                          "type": "array"
                        },
                        "decisionEmail": {
                          "description": "Mail open questions 14 / 3 / 0 days before their 判断の目安日 (review_by), and once if it passed unreminded. Default true (BE ADR-0025).",
                          "type": "boolean"
                        },
                        "hasEmail": {
                          "type": "boolean"
                        },
                        "weeklyDigestEmail": {
                          "description": "The Monday 「今週のまとめ」 (this week, overdue, 判断の目安日, unrecorded 納付・控え) inside that day's one reminder mail; left out when empty. Default true (BE ADR-0025).",
                          "type": "boolean"
                        }
                      },
                      "required": [
                        "hasEmail",
                        "deadlineEmail",
                        "weeklyDigestEmail",
                        "decisionEmail",
                        "calendarOwnedReminderTypes",
                        "deadlineBeforeDays",
                        "deadlineOverdueRepeat",
                        "deadlineBeforeDayOptions",
                        "deadlineStandardBeforeDays"
                      ],
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "The switches after the update"
          },
          "400": {
            "description": "Invalid body"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "User profile not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Change deadline reminder mail: on / off, which days before, and repeats after the date",
        "tags": [
          "Reminders"
        ]
      }
    },
    "/reminders/statutory-metadata": {
      "get": {
        "description": "Retrieve metadata for all statutory task types including actions, recipients, and submission methods.\n\n## Statutory Task Metadata\nReturns configuration data for each statutory task type:\n- **Actions**: List of actions for each task type\n- **Recipients**: Who receives each action\n- **Submission Methods**: How to submit each action\n- **Conditions**: When conditional actions apply\n\n## Use Cases\n- **UI Configuration**: Use to render task details without hardcoding\n- **Validation**: Understand which actions are required vs conditional\n- **Localization**: Japanese labels for all fields\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/StatutoryTaskMetadataResponse"
                }
              }
            },
            "description": "Statutory task metadata retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get statutory task metadata",
        "tags": [
          "Reminders"
        ]
      }
    },
    "/reminders/{id}/actions/{action_id}/done": {
      "patch": {
        "description": "Toggle the completion status of a specific action within a statutory task.\n\n## Per-Action Completion (アクション別完了)\nMark individual actions as complete/incomplete:\n- **Independent Tracking**: Each action can be completed independently\n- **Toggle Behavior**: Calling again will toggle the status\n- **Audit Trail**: All completion changes are logged\n\n## Example Usage\nFor 源泉徴収票:\n1. Complete \"交付 to 従業員\" → action marked done\n2. If condition met, complete \"提出 to 税務署\" → action marked done\n3. When ALL required actions done → reminder is_done = true\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "System reminder ID (e.g., system-withholding-tax-slip-2026)",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "Action ID from statutory_task_actions",
            "in": "path",
            "name": "action_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ActionCompletionResponse"
                }
              }
            },
            "description": "Action completion status toggled successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Action not found",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Action not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Toggle action completion status",
        "tags": [
          "Reminders"
        ]
      }
    },
    "/reminders/{id}/done": {
      "patch": {
        "description": "Mark a reminder as completed for the authenticated user.\n\n## Reminder Completion (リマインダー完了)\nComprehensive completion tracking with:\n- **Status Update**: Mark reminder as completed with timestamp\n- **User Validation**: Ensure user can only update their own reminders\n- **Audit Trail**: Complete audit trail of completion actions\n- **Next Occurrence**: Automatic scheduling of next occurrence for recurring reminders\n- **Notification Update**: Update notification schedules based on completion\n\n## Completion Process\n- **Ownership Verification**: Verify user owns the reminder before updating\n- **Status Update**: Mark reminder as done with completion timestamp\n- **Recurring Logic**: Calculate and schedule next occurrence for recurring reminders\n- **Audit Logging**: Log completion action for audit and compliance\n- **Notification Management**: Update or remove associated notifications\n\n## Recurring Reminder Handling\n- **Monthly Reminders**: Schedule next month's occurrence\n- **Yearly Reminders**: Schedule next year's occurrence\n- **Weekly Reminders**: Schedule next week's occurrence\n- **One-Time Reminders**: Mark as completed without rescheduling\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Reminder ID to mark as done",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ReminderActionResponse"
                }
              }
            },
            "description": "Reminder marked as done successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Reminder not found",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Reminder not found"
          },
          "409": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Reminder is already marked as done",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Reminder already completed"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Mark reminder as done",
        "tags": [
          "Reminders"
        ]
      }
    },
    "/reports/amendment-working-paper": {
      "get": {
        "description": "Server-built accountant working paper from received filings, bank, ledger, assets, and amendments. Client-supplied figures are not accepted.",
        "parameters": [
          {
            "in": "query",
            "name": "fiscal_year",
            "required": true,
            "schema": {
              "maximum": 2100,
              "minimum": 2000,
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "scope",
            "required": false,
            "schema": {
              "enum": [
                "corporate",
                "consumption"
              ],
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "additionalProperties": true,
                      "description": "Without `scope`: the packet for both scopes (canonicalWorkingPaperService.build). With `scope`: that one scope model (buildScope).",
                      "type": "object"
                    },
                    "message": {
                      "example": "Success",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Canonical working-paper packet or a single scope model"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Canonical 修正・更正の経緯 model",
        "tags": [
          "Financial Reports"
        ]
      }
    },
    "/reports/amendment-working-paper/export": {
      "post": {
        "description": "Renders the canonical working paper. Body is fiscal_year + scope + format. Client-supplied provenance is rejected.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "fiscal_year": {
                    "maximum": 2100,
                    "minimum": 2000,
                    "type": "integer"
                  },
                  "format": {
                    "default": "pdf",
                    "enum": [
                      "pdf",
                      "xlsx"
                    ],
                    "type": "string"
                  },
                  "scope": {
                    "enum": [
                      "corporate",
                      "consumption"
                    ],
                    "type": "string"
                  }
                },
                "required": [
                  "fiscal_year",
                  "scope"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/pdf": {
                "schema": {
                  "format": "binary",
                  "type": "string"
                }
              },
              "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": {
                "schema": {
                  "format": "binary",
                  "type": "string"
                }
              }
            },
            "description": "PDF or XLSX file download"
          },
          "400": {
            "description": "Invalid body or client-supplied provenance"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Export 修正・更正の経緯 (PDF or Excel)",
        "tags": [
          "Financial Reports"
        ]
      }
    },
    "/reports/balance-sheet": {
      "get": {
        "description": "Generate comprehensive balance sheet following Japanese accounting standards.\n\n## Balance Sheet (貸借対照表)\nStandard Japanese balance sheet with:\n- **Asset Classification**: Current assets, fixed assets, and deferred assets\n- **Liability Structure**: Current liabilities and long-term liabilities\n- **Equity Analysis**: Capital, retained earnings, and current year profit\n- **Balance Verification**: Mathematical verification of balance sheet accuracy\n- **Period Comparison**: Current vs. prior period comparison analysis\n- **Japanese Standards**: Full compliance with Japanese accounting standards\n\n## Balance Sheet Sections\n- **Assets (資産の部)**:\n  - Current Assets (流動資産): Cash, receivables, inventory\n  - Fixed Assets (固定資産): Tangible, intangible, investments\n  - Deferred Assets (繰延資産): Deferred charges and expenses\n- **Liabilities (負債の部)**:\n  - Current Liabilities (流動負債): Short-term obligations\n  - Long-term Liabilities (固定負債): Long-term debt and obligations\n- **Equity (純資産の部)**:\n  - Capital (資本金): Paid-in capital\n  - Retained Earnings (利益剰余金): Accumulated profits\n  - Current Year Profit (当期純利益): Current year net income\n\n## Use Cases\n- **Financial Position Analysis**: Analyze company's financial position\n- **Liquidity Assessment**: Assess liquidity and financial health\n- **Investor Reporting**: Provide balance sheet for investors\n- **Credit Analysis**: Support credit applications and analysis\n- **Compliance Reporting**: Meet regulatory reporting requirements\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "As-of date for balance sheet (defaults to current date)",
            "in": "query",
            "name": "asOfDate",
            "required": false,
            "schema": {
              "$ref": "#/components/schemas/DateFormat"
            }
          },
          {
            "description": "Include prior period comparison",
            "in": "query",
            "name": "compareWithPrior",
            "required": false,
            "schema": {
              "default": false,
              "type": "boolean"
            }
          },
          {
            "description": "Prior period as-of date for comparison",
            "in": "query",
            "name": "priorAsOfDate",
            "required": false,
            "schema": {
              "$ref": "#/components/schemas/DateFormat"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/BalanceSheetStatement"
                    },
                    "message": {
                      "example": "Balance sheet generated successfully",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Balance sheet generated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Generate balance sheet (貸借対照表)",
        "tags": [
          "Financial Reports"
        ]
      }
    },
    "/reports/cash-flow": {
      "get": {
        "description": "Generate comprehensive cash flow statement following Japanese accounting standards.\n\n## Cash Flow Statement (キャッシュフロー計算書)\nStandard Japanese cash flow analysis with:\n- **Operating Activities (営業活動)**: Cash flows from core business operations\n- **Investing Activities (投資活動)**: Cash flows from investments and asset transactions\n- **Financing Activities (財務活動)**: Cash flows from financing and capital transactions\n- **Net Cash Flow**: Net change in cash position during the period\n- **Period Comparison**: Current vs. prior period cash flow analysis\n- **Cash Position**: Beginning and ending cash positions\n\n## Cash Flow Categories\n- **Operating Cash Flow**: Revenue collection, expense payments, working capital changes\n- **Investing Cash Flow**: Asset purchases, disposals, and investment activities\n- **Financing Cash Flow**: Debt transactions, equity transactions, dividend payments\n- **Free Cash Flow**: Operating cash flow minus capital expenditures\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Period start date",
            "in": "query",
            "name": "startDate",
            "required": false,
            "schema": {
              "$ref": "#/components/schemas/DateFormat"
            }
          },
          {
            "description": "Period end date",
            "in": "query",
            "name": "endDate",
            "required": false,
            "schema": {
              "$ref": "#/components/schemas/DateFormat"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FinancialReportResponse"
                }
              }
            },
            "description": "Cash flow statement generated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Generate cash flow statement (キャッシュフロー計算書)",
        "tags": [
          "Financial Reports"
        ]
      }
    },
    "/reports/cash-forecast": {
      "get": {
        "description": "13-week 資金繰り forecast built only from cash events the app already holds (BL-052).\n\nThe weeks start from the latest bank balance of the company accounts and move only by dated events:\n- **Inflows**: open sales invoices (no linked deposit, payments below total) on their due date.\n- **Payables**: unpaid card statements on their 引落日.\n- **Taxes**: open deadline-spine rows that move cash (消費税, 法人税, 中間, 源泉, 労働保険) and unpaid\n  office_tax_payments. 消費税 amounts come from a filed or generated return of the same period, else the\n  stored 課税期間 result, else the 消費税 engine's current calculation for the unfiled period; 源泉 amounts come\n  from the withholding register. A refund is an `in` event 「消費税の還付見込み」 with its amount and\n  countsInBalance false: its 入金日 is unknown, so no week or balance includes it.\n- **Recurring**: 役員報酬 from the compensation schedule on the pay-slip day, 社会保険料 from that month's\n  notice, and contracts (business_agreements) with an amount and cadence.\n\nNo figure is averaged or extrapolated. An event no record prices has amount null (金額未確定); it is counted in\nunknownAmountCount and in its week's unknownAmountCount, not in the balances. With no bank balance on file\nstartingBalance is null and no week is marked caution or danger.\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Number of days to forecast (default: 90 days)",
            "in": "query",
            "name": "days",
            "required": false,
            "schema": {
              "default": 90,
              "maximum": 365,
              "minimum": 7,
              "type": "integer"
            }
          },
          {
            "description": "BL-975 what-if: price every regular 役員報酬 event paid on or after officerCompFrom at this monthly amount (0 drops them). Response only; nothing is written. Send with officerCompFrom.",
            "in": "query",
            "name": "officerCompMonthly",
            "required": false,
            "schema": {
              "maximum": 100000000,
              "minimum": 0,
              "type": "integer"
            }
          },
          {
            "description": "BL-975 what-if: first payday date (YYYY-MM-DD) the scenario applies to. Send with officerCompMonthly.",
            "in": "query",
            "name": "officerCompFrom",
            "required": false,
            "schema": {
              "example": "2027-02-16",
              "format": "date",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "allOf": [
                    {
                      "$ref": "#/components/schemas/FinancialReportResponse"
                    },
                    {
                      "properties": {
                        "data": {
                          "$ref": "#/components/schemas/CashFlowForecast"
                        }
                      },
                      "type": "object"
                    }
                  ]
                }
              }
            },
            "description": "Cash flow forecast generated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Generate cash flow forecast (資金繰り予測)",
        "tags": [
          "Financial Reports"
        ]
      }
    },
    "/reports/expense-analytics": {
      "get": {
        "description": "Generate comprehensive expense analytics and cost management analysis.\n\n## Expense Analytics (経費分析)\nAdvanced expense analysis with:\n- **Cost Categorization**: Detailed expense categorization and analysis\n- **Trend Analysis**: Historical expense trends and patterns\n- **Budget Variance**: Budget vs. actual expense analysis\n- **Cost Control**: Identify cost control opportunities and recommendations\n- **Department Analysis**: Department-based expense breakdown\n- **Vendor Analysis**: Vendor spending analysis and optimization\n\n## Analytics Components\n- **Expense Breakdown**: Detailed expense categorization\n- **Trend Analysis**: Period-over-period expense trends\n- **Budget Analysis**: Budget variance and performance analysis\n- **Cost Optimization**: Identify cost reduction opportunities\n- **Department Insights**: Department-based cost analysis\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Analysis start date",
            "in": "query",
            "name": "startDate",
            "required": false,
            "schema": {
              "$ref": "#/components/schemas/DateFormat"
            }
          },
          {
            "description": "Analysis end date",
            "in": "query",
            "name": "endDate",
            "required": false,
            "schema": {
              "$ref": "#/components/schemas/DateFormat"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FinancialReportResponse"
                }
              }
            },
            "description": "Expense analytics generated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Generate expense analytics (経費分析)",
        "tags": [
          "Financial Reports"
        ]
      }
    },
    "/reports/financial-summary": {
      "get": {
        "description": "Composite endpoint returning trial balance, profit & loss, and balance sheet headline numbers in a single call.\n\n## Purpose\nReplaces 3 separate API calls for the Financial Charts dock with 1 request.\n\n## What's Included\n- **Trial Balance**: Account count, debit/credit totals, balance check, discrepancy\n- **Profit & Loss**: Revenue, expenses, net income, operating income, gross profit\n- **Balance Sheet**: Assets, liabilities, equity, balance check\n\n## Performance\n- **Target**: <300ms response time\n- **Caching**: 120-second per-user memory cache\n- **Queries**: 3 parallel service calls via Promise.all()\n\n## Currency\nAll monetary values are **integer JPY** (no decimals).",
        "parameters": [
          {
            "description": "Start date in YYYYMMDD format (defaults to fiscal year start)",
            "example": "20250401",
            "in": "query",
            "name": "start_date",
            "required": false,
            "schema": {
              "pattern": "^\\d{8}$",
              "type": "string"
            }
          },
          {
            "description": "End date in YYYYMMDD format (defaults to fiscal year end)",
            "example": "20260331",
            "in": "query",
            "name": "end_date",
            "required": false,
            "schema": {
              "pattern": "^\\d{8}$",
              "type": "string"
            }
          },
          {
            "description": "As-of date for balance sheet (defaults to end_date)",
            "example": "20260216",
            "in": "query",
            "name": "as_of_date",
            "required": false,
            "schema": {
              "pattern": "^\\d{8}$",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/FinancialSummaryResponse"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Financial summary generated successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get composite financial summary (TB + P&L + BS)",
        "tags": [
          "Financial Reports"
        ]
      }
    },
    "/reports/insights": {
      "get": {
        "description": "Generate AI-powered business insights and recommendations for strategic decision making.\n\n## Business Insights (経営インサイト)\nAI-powered business analysis with:\n- **Performance Analysis**: Comprehensive business performance analysis\n- **Trend Identification**: Identify key business trends and patterns\n- **Risk Assessment**: Assess financial and operational risks\n- **Opportunity Identification**: Identify growth opportunities and optimization areas\n- **Strategic Recommendations**: AI-powered strategic recommendations\n- **Competitive Analysis**: Industry benchmarking and competitive positioning\n\n## Insight Categories\n- **Financial Health**: Overall financial health assessment\n- **Operational Efficiency**: Operational performance and efficiency analysis\n- **Growth Opportunities**: Identify areas for business growth\n- **Risk Factors**: Identify and assess business risks\n- **Strategic Recommendations**: Actionable strategic recommendations\n\n## AI-Powered Features\n- **Pattern Recognition**: Identify patterns in financial and operational data\n- **Predictive Analytics**: Predict future performance and trends\n- **Anomaly Detection**: Detect unusual patterns and potential issues\n- **Benchmarking**: Compare performance against industry benchmarks\n- **Optimization**: Recommend optimization strategies and improvements\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Analysis start date",
            "in": "query",
            "name": "startDate",
            "required": false,
            "schema": {
              "$ref": "#/components/schemas/DateFormat"
            }
          },
          {
            "description": "Analysis end date",
            "in": "query",
            "name": "endDate",
            "required": false,
            "schema": {
              "$ref": "#/components/schemas/DateFormat"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FinancialReportResponse"
                }
              }
            },
            "description": "Business insights generated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Generate business insights (経営インサイト)",
        "tags": [
          "Financial Reports"
        ]
      }
    },
    "/reports/kpi-dashboard": {
      "get": {
        "description": "Generate comprehensive KPI dashboard with Japanese business analytics and insights.\n\n## KPI Dashboard (経営指標ダッシュボード)\nComprehensive business analytics with:\n- **Profitability Metrics (収益性指標)**: Gross margin, operating margin, net margin, ROA\n- **Liquidity Metrics (流動性指標)**: Current ratio, quick ratio, cash ratio\n- **Efficiency Metrics (効率性指標)**: Asset turnover, receivables turnover, DSO\n- **Growth Metrics (成長性指標)**: Revenue growth, profit growth, asset growth\n- **Cash Flow Metrics (キャッシュフロー指標)**: Operating cash flow, free cash flow, cash balance, bank balance (v3.1)\n- **Business Alerts**: AI-powered business insights and recommendations (v3.1: reconciliation gap alerts)\n- **Historical Trends**: Multi-year trend analysis for strategic planning\n\n## KPI Categories\n- **Profitability Analysis**: Analyze profit margins and return on assets\n- **Liquidity Assessment**: Assess short-term financial health\n- **Operational Efficiency**: Measure operational efficiency and asset utilization\n- **Growth Analysis**: Track business growth and expansion metrics\n- **Cash Management**: Monitor cash flow and liquidity position\n\n## Alert System\n- **Critical Alerts**: Issues requiring immediate attention\n- **Warning Alerts**: Issues requiring monitoring and action\n- **Success Alerts**: Positive performance indicators\n- **Recommendations**: AI-powered business recommendations\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Period start date (defaults to fiscal year start)",
            "in": "query",
            "name": "startDate",
            "required": false,
            "schema": {
              "$ref": "#/components/schemas/DateFormat"
            }
          },
          {
            "description": "Period end date (defaults to current date)",
            "in": "query",
            "name": "endDate",
            "required": false,
            "schema": {
              "$ref": "#/components/schemas/DateFormat"
            }
          },
          {
            "description": "Include prior period comparison for trend analysis",
            "in": "query",
            "name": "includePriorPeriod",
            "required": false,
            "schema": {
              "default": true,
              "type": "boolean"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/KPIDashboard"
                    },
                    "message": {
                      "example": "KPI dashboard generated successfully",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "KPI dashboard generated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Generate KPI dashboard (経営指標ダッシュボード)",
        "tags": [
          "Financial Reports"
        ]
      }
    },
    "/reports/profit-loss": {
      "get": {
        "description": "Generate comprehensive profit and loss statement following Japanese accounting standards.\n\n## Profit & Loss Statement (損益計算書)\nStandard Japanese P&L with:\n- **Revenue Analysis**: Comprehensive revenue breakdown and analysis\n- **Cost Management**: Cost of sales and operating expense analysis\n- **Profitability Metrics**: Gross profit, operating income, ordinary income, net income\n- **Period Comparison**: Current vs. prior period variance analysis\n- **Japanese Format**: Standard Japanese P&L statement format\n- **Margin Analysis**: Profit margin calculations and trend analysis\n\n## Statement Sections\n- **Revenue (売上高)**: Sales revenue and other income\n- **Cost of Sales (売上原価)**: Direct costs and cost of goods sold\n- **Gross Profit (売上総利益)**: Revenue minus cost of sales\n- **Operating Expenses (販管費)**: Selling, general, and administrative expenses\n- **Operating Income (営業利益)**: Operating profit before non-operating items\n- **Ordinary Income (経常利益)**: Operating income plus non-operating income\n- **Net Income (当期純利益)**: Final profit after all expenses and taxes\n\n## Use Cases\n- **Financial Analysis**: Comprehensive profitability analysis\n- **Management Reporting**: Executive and management financial reporting\n- **Investor Relations**: Financial reporting for investors and stakeholders\n- **Tax Preparation**: Prepare financial data for tax filing\n- **Performance Review**: Analyze business performance and trends\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Period start date (defaults to fiscal year start)",
            "in": "query",
            "name": "startDate",
            "required": false,
            "schema": {
              "$ref": "#/components/schemas/DateFormat"
            }
          },
          {
            "description": "Period end date (defaults to current date)",
            "in": "query",
            "name": "endDate",
            "required": false,
            "schema": {
              "$ref": "#/components/schemas/DateFormat"
            }
          },
          {
            "description": "Include prior period comparison",
            "in": "query",
            "name": "includePriorPeriod",
            "required": false,
            "schema": {
              "default": true,
              "type": "boolean"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/ProfitLossStatement"
                    },
                    "message": {
                      "example": "Profit and loss statement generated successfully",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Profit and loss statement generated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Generate profit and loss statement (損益計算書)",
        "tags": [
          "Financial Reports"
        ]
      }
    },
    "/reports/revenue-analytics": {
      "get": {
        "description": "Generate comprehensive revenue analytics and sales performance analysis.\n\n## Revenue Analytics (売上分析)\nAdvanced sales analysis with:\n- **Revenue Trends**: Historical revenue trends and growth analysis\n- **Customer Analysis**: Customer-based revenue breakdown and analysis\n- **Product Analysis**: Product/service revenue performance\n- **Seasonal Patterns**: Identify seasonal revenue patterns and cycles\n- **Growth Metrics**: Revenue growth rates and performance indicators\n- **Forecasting**: Revenue forecasting based on historical patterns\n\n## Analytics Components\n- **Revenue Breakdown**: Detailed revenue categorization and analysis\n- **Growth Analysis**: Period-over-period growth analysis\n- **Customer Insights**: Top customers and revenue concentration\n- **Trend Analysis**: Long-term revenue trends and patterns\n- **Performance Metrics**: Key revenue performance indicators\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Analysis start date",
            "in": "query",
            "name": "startDate",
            "required": false,
            "schema": {
              "$ref": "#/components/schemas/DateFormat"
            }
          },
          {
            "description": "Analysis end date",
            "in": "query",
            "name": "endDate",
            "required": false,
            "schema": {
              "$ref": "#/components/schemas/DateFormat"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FinancialReportResponse"
                }
              }
            },
            "description": "Revenue analytics generated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Generate revenue analytics (売上分析)",
        "tags": [
          "Financial Reports"
        ]
      }
    },
    "/reports/trial-balance": {
      "get": {
        "description": "Generate comprehensive trial balance report for Japanese accounting compliance.\n\n## Trial Balance Report (試算表)\nStandard Japanese trial balance with:\n- **Account Balancing**: Comprehensive account balance verification\n- **Period Comparison**: Current vs. prior period analysis\n- **Japanese Format**: Standard Japanese trial balance format\n- **Account Categories**: Organized by asset, liability, equity, revenue, expense\n- **Balance Verification**: Ensure debits equal credits for accounting accuracy\n- **Audit Compliance**: Audit-ready trial balance for compliance review\n\n## Report Features\n- **Opening Balances**: Beginning balances for each account\n- **Period Activity**: Transaction activity during the specified period\n- **Closing Balances**: Ending balances after period activity\n- **Variance Analysis**: Comparison with prior period balances\n- **Account Hierarchy**: Organized account hierarchy for easy review\n- **Balance Validation**: Mathematical validation of trial balance accuracy\n\n## Use Cases\n- **Monthly Closing**: Monthly trial balance for accounting periods\n- **Audit Preparation**: Prepare trial balance for audit review\n- **Financial Analysis**: Analyze account balances and trends\n- **Compliance Reporting**: Generate reports for regulatory compliance\n- **Management Review**: Provide management with account balance overview\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Period start date (defaults to fiscal year start)",
            "in": "query",
            "name": "startDate",
            "required": false,
            "schema": {
              "$ref": "#/components/schemas/DateFormat"
            }
          },
          {
            "description": "Period end date (defaults to current date)",
            "in": "query",
            "name": "endDate",
            "required": false,
            "schema": {
              "$ref": "#/components/schemas/DateFormat"
            }
          },
          {
            "description": "Include prior period comparison",
            "in": "query",
            "name": "includePriorPeriod",
            "required": false,
            "schema": {
              "default": true,
              "type": "boolean"
            }
          },
          {
            "description": "Prior period start date",
            "in": "query",
            "name": "priorStartDate",
            "required": false,
            "schema": {
              "$ref": "#/components/schemas/DateFormat"
            }
          },
          {
            "description": "Prior period end date",
            "in": "query",
            "name": "priorEndDate",
            "required": false,
            "schema": {
              "$ref": "#/components/schemas/DateFormat"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FinancialReportResponse"
                }
              }
            },
            "description": "Trial balance report generated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Generate trial balance report (試算表)",
        "tags": [
          "Financial Reports"
        ]
      }
    },
    "/reports/validation": {
      "get": {
        "description": "Get comprehensive accounting data validation report including health status and all problematic transactions.\n\n## Validation Report (会計データ検証)\nComprehensive accounting validation with:\n- **Trial Balance Check**: Verifies total debits equal total credits\n- **Accounting Equation**: Verifies Assets = Liabilities + Equity + Net Income\n- **Issue Detection**: Identifies problematic transactions and entries\n- **Health Score**: Overall accounting health assessment\n\n## Issue Types Detected\n- **UNBALANCED**: Journal entry where debit ≠ credit\n- **ORPHAN_ENTRY**: Journal entry with no lines\n- **NEGATIVE_DEBIT_ACCOUNT**: Asset/expense with negative balance\n- **NEGATIVE_CREDIT_ACCOUNT**: Liability/revenue with negative balance\n- **POTENTIAL_DUPLICATE**: Same date, amount, description\n\n## Use Cases\n- **Period Close Checklist**: Run before closing accounting period\n- **Audit Preparation**: Identify data quality issues before audit\n- **Continuous Monitoring**: Regular health checks for data integrity\n- **Issue Resolution**: Get list of transactions needing attention\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/FullValidationResponse"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Validation report generated successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Full accounting validation report (会計データ検証)",
        "tags": [
          "Financial Reports"
        ]
      }
    },
    "/reports/validation/health": {
      "get": {
        "description": "Get quick accounting health status for UI indicators and dashboards.\n\n## Health Check (会計ヘルスチェック)\nQuick validation status with:\n- **Health Status**: healthy/warning/critical indicator\n- **Trial Balance**: Debit/credit balance verification\n- **Accounting Equation**: Assets = Liabilities + Equity check\n- **Issue Counts**: Number of errors and warnings\n- **Financial Totals**: Summary of account totals\n\n## v3.1 Enhancements (additive, backward compatible)\n- **Reconciliation Progress**: All 5 statuses (pending/matched/partially_matched/excluded/suspense), unjournalized amounts\n- **Cash Balance Sources**: Dual balance (journal-derived vs bank-statement), gap analysis with direction\n- **Journal Completeness**: processedCount, journalizedCount, completionRate, journalizationRate\n- **Cache**: 30s server cache (maxAge: 30, staleWhileRevalidate: 15) — aligns with FE staleTime: 30_000\n\n## Health Status Levels\n- **healthy**: No issues detected, accounting data is clean\n- **warning**: Minor issues detected, review recommended\n- **critical**: Major issues detected, immediate attention required\n\n## Use Cases\n- **Dashboard Indicator**: Show health badge in UI\n- **Quick Check**: Fast validation before generating reports\n- **Monitoring**: Regular polling for status changes\n- **KPI Dashboard Integration**: Reconciliation badge, cash gap warning (v3.1)\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Period start (YYYYMMDD). Send start_date and end_date together or not at all: together they scope journal-derived cash to the period, a lone bound is a 400 validation error, and omitting both gives all-time.",
            "in": "query",
            "name": "start_date",
            "required": false,
            "schema": {
              "pattern": "^\\d{8}$",
              "type": "string"
            }
          },
          {
            "description": "Period end (YYYYMMDD). Must be sent together with start_date.",
            "in": "query",
            "name": "end_date",
            "required": false,
            "schema": {
              "pattern": "^\\d{8}$",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/AccountingHealthResponse"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Health check completed successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Quick accounting health check (会計ヘルスチェック)",
        "tags": [
          "Financial Reports"
        ]
      }
    },
    "/reports/validation/problems": {
      "get": {
        "description": "Get list of transactions with accounting issues for frontend display and resolution.\n\n## Problematic Transactions (問題のある取引)\nDetailed list of issues with:\n- **Transaction Details**: Entry number, description, amount\n- **Issue Type**: Specific issue identified\n- **Issue Description**: Human-readable explanation\n- **Severity**: Error or warning level\n- **Created Date**: When transaction was created\n\n## Issue Types\n| Type | Severity | Description |\n|------|----------|-------------|\n| UNBALANCED | error | Journal debit ≠ credit |\n| ORPHAN_ENTRY | error | Entry has no lines |\n| NEGATIVE_DEBIT_ACCOUNT | warning | Asset/expense negative |\n| NEGATIVE_CREDIT_ACCOUNT | warning | Liability/revenue negative |\n| POTENTIAL_DUPLICATE | warning | Duplicate entry detected |\n\n## Use Cases\n- **Issue Resolution**: Display list for user to fix issues\n- **Data Cleanup**: Identify and correct data quality issues\n- **Audit Trail**: Document issues found during validation\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Maximum number of problems to return (default: 50)",
            "in": "query",
            "name": "limit",
            "required": false,
            "schema": {
              "default": 50,
              "maximum": 500,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/ValidationProblemsResponse"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Problems retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get problematic transactions (問題のある取引)",
        "tags": [
          "Financial Reports"
        ]
      }
    },
    "/reports/worksheet": {
      "get": {
        "description": "Per-account posted activity split into 試算表 (pre-adjustment) and 修正記入 (adjustment) column groups for the 8-column 精算表. The frontend derives the 損益計算書 / 貸借対照表 columns from `category` and the net of these figures.\n\n## Query Parameters\n- **startDate**: Period start (YYYYMMDD)\n- **endDate**: Period end (YYYYMMDD)\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "期間開始日 (YYYYMMDD)",
            "in": "query",
            "name": "startDate",
            "required": true,
            "schema": {
              "example": 20260101,
              "type": "integer"
            }
          },
          {
            "description": "期間終了日 (YYYYMMDD)",
            "in": "query",
            "name": "endDate",
            "required": true,
            "schema": {
              "example": 20261231,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/WorksheetResponse"
                }
              }
            },
            "description": "Worksheet retrieved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Generate worksheet (精算表)",
        "tags": [
          "Financial Reports"
        ]
      }
    },
    "/sales-invoices": {
      "get": {
        "description": "Retrieve a paginated list of sales invoices with optional filtering by client, date range, and other criteria.\n\n## Query Parameters\n- **client_id**: Filter invoices by specific client\n- **start_date**: Filter invoices from this date (Unix timestamp)\n- **end_date**: Filter invoices until this date (Unix timestamp)\n- **page**: Page number for pagination (default: 1)\n- **limit**: Number of invoices per page (default: 20, max: 100)\n\n## Pagination\nResults are paginated with metadata including:\n- Total count of matching invoices\n- Current page and limit\n- Total pages and navigation flags\n- Boolean indicators for next/previous pages\n\n## Date Filtering\n- Dates are provided as Unix timestamps\n- Filtering is based on invoice issue date\n- Both start_date and end_date are optional\n\n## Security\nOnly returns invoices belonging to the authenticated user.\n\n## Use Cases\n- Invoice management dashboards\n- Client-specific invoice views\n- Financial reporting and analysis\n- Date-range based invoice queries\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Filter by client identifier",
            "in": "query",
            "name": "client_id",
            "required": false,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Filter from this date (Unix timestamp)",
            "example": 1640995200,
            "in": "query",
            "name": "start_date",
            "required": false,
            "schema": {
              "type": "integer"
            }
          },
          {
            "description": "Filter until this date (Unix timestamp)",
            "example": 1643673600,
            "in": "query",
            "name": "end_date",
            "required": false,
            "schema": {
              "type": "integer"
            }
          },
          {
            "description": "Page number for pagination",
            "in": "query",
            "name": "page",
            "required": false,
            "schema": {
              "default": 1,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "description": "Number of invoices per page",
            "in": "query",
            "name": "limit",
            "required": false,
            "schema": {
              "default": 20,
              "maximum": 100,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SalesInvoiceListResponse"
                }
              }
            },
            "description": "Sales invoices retrieved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List sales invoices with filtering and pagination",
        "tags": [
          "Sales Invoices"
        ]
      },
      "post": {
        "description": "Create a new sales invoice with complete invoice details and line items.\n\n## Request Body\nThe request must include:\n- **document_id**: Associated document identifier\n- **issue_date** and **due_date**: Invoice dates as Unix timestamps\n- **project_title**: Description of the work or project\n- **client_id**: Client identifier\n- **subtotal**, **tax**, **total**: Financial amounts\n- **items**: Array of invoice line items\n\n## Invoice Items\nEach item must include:\n- **item**: Item name or description\n- **quantity**: Quantity as string (supports various formats)\n- **unitPrice**: Price per unit\n- **amount**: Total amount (quantity × unitPrice)\n\n## Optional Fields\n- **invoice_number**: Auto-generated if not provided\n- **period_start/end**: Project period dates\n- **quote_number/order_number**: Related document numbers\n- **payment_info**: Bank account and payment details\n- **notes**: Additional invoice notes\n\n## Business Logic\n- Invoice numbers are auto-generated if not provided\n- Total amounts are validated for consistency\n- Client must exist and belong to the user\n- Document must exist and be accessible\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateSalesInvoiceRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SalesInvoiceCreateResponse"
                }
              }
            },
            "description": "Sales invoice created successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "409": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "DUPLICATE_INVOICE",
                      "type": "string"
                    },
                    "error": {
                      "example": "Sales invoice already exists: INV-2024-001",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Duplicate invoice detected"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create a new sales invoice",
        "tags": [
          "Sales Invoices"
        ]
      }
    },
    "/sales-invoices/document/{document_id}": {
      "get": {
        "description": "Retrieve a sales invoice associated with a specific document.\n\n## Path Parameters\n- **document_id**: UUID of the document to find invoice for\n\n## Response Data\nReturns the invoice created from or associated with the specified document.\nThis is useful for:\n- Finding invoices generated from processed documents\n- Linking document processing results to invoices\n- Document-to-invoice workflow tracking\n\n## Document Association\nInvoices are linked to documents through:\n- Document-based invoice creation\n- Manual document association\n- Processing workflow connections\n\n## Security\nOnly allows access to invoices belonging to the authenticated user.\n\n## Use Cases\n- Document processing workflows\n- Invoice-document relationship tracking\n- Finding invoices from uploaded documents\n- Integration with document management\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the document to find invoice for",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SalesInvoiceResponse"
                }
              }
            },
            "description": "Sales invoice retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "ACCESS_DENIED",
                      "type": "string"
                    },
                    "error": {
                      "example": "Access denied",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Access denied - document belongs to different user"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get sales invoice by document ID",
        "tags": [
          "Sales Invoices"
        ]
      }
    },
    "/sales-invoices/from-document/{document_id}": {
      "post": {
        "description": "Create a new sales invoice by processing and extracting data from an existing document.\n\n## Path Parameters\n- **document_id**: UUID of the document to process\n\n## Document Processing\nThis endpoint:\n- Analyzes the specified document using AI/OCR\n- Extracts invoice-relevant information\n- Creates a structured invoice from the extracted data\n- Links the invoice to the source document\n\n## Extracted Information\nThe system attempts to extract:\n- Client information and details\n- Project title and description\n- Line items with quantities and pricing\n- Dates (issue date, due date, periods)\n- Financial totals and tax information\n- Payment terms and notes\n\n## Processing Time\nDocument processing may take several seconds to complete.\nThe operation includes:\n- Document text extraction\n- AI-powered data extraction\n- Data validation and structuring\n- Invoice creation and storage\n\n## Error Handling\nCommon processing errors:\n- Document not found or inaccessible\n- Document format not supported\n- Insufficient data for invoice creation\n- AI processing failures\n\n## Use Cases\n- Automated invoice creation from scanned documents\n- Bulk invoice processing workflows\n- Document digitization and structuring\n- Integration with document management systems\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the document to process",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SalesInvoiceCreateResponse"
                }
              }
            },
            "description": "Sales invoice created from document successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "PROCESSING_ERROR",
                      "type": "string"
                    },
                    "error": {
                      "example": "Document processing failed",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Document processing failed or invalid document"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "ACCESS_DENIED",
                      "type": "string"
                    },
                    "error": {
                      "example": "Access denied",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Access denied - document belongs to different user"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create invoice from document",
        "tags": [
          "Sales Invoices"
        ]
      }
    },
    "/sales-invoices/{invoice_id}": {
      "delete": {
        "description": "Delete a sales invoice and all associated data.\n\n## Path Parameters\n- **invoice_id**: UUID of the invoice to delete\n\n## Deletion Behavior\n- Permanently removes the invoice from the database\n- Cascades to related line items and attachments\n- Cannot be undone - use with caution\n- Returns success even if invoice doesn't exist\n\n## Impact of Deletion\nRemoving an invoice will affect:\n- Financial reporting and totals\n- Client invoice history\n- Related journal entries (if generated)\n- Document associations\n\n## Security Considerations\n- Operation is logged for audit purposes\n- Only allows deletion of user's own invoices\n- Immediate effect - no soft delete\n\n## Use Cases\n- Correcting invoice creation errors\n- Removing duplicate invoices\n- Data cleanup and maintenance\n- Compliance with data retention policies\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the invoice to delete",
            "in": "path",
            "name": "invoice_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SalesInvoiceDeleteResponse"
                }
              }
            },
            "description": "Sales invoice deleted successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "ACCESS_DENIED",
                      "type": "string"
                    },
                    "error": {
                      "example": "Access denied",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Access denied - invoice belongs to different user"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Delete a sales invoice",
        "tags": [
          "Sales Invoices"
        ]
      },
      "get": {
        "description": "Retrieve a specific sales invoice by its unique identifier.\n\n## Path Parameters\n- **invoice_id**: UUID of the invoice to retrieve\n\n## Response Data\nReturns complete invoice information including:\n- Invoice header information (dates, numbers, client)\n- Project details and period information\n- Financial amounts (subtotal, tax, total)\n- Line items with quantities and pricing\n- Payment information and notes\n- Audit timestamps\n\n## Security\nOnly allows access to invoices belonging to the authenticated user.\n\n## Use Cases\n- Invoice detail views\n- Invoice editing forms\n- Financial reporting\n- Client invoice history\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the invoice to retrieve",
            "in": "path",
            "name": "invoice_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SalesInvoiceResponse"
                }
              }
            },
            "description": "Sales invoice retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "ACCESS_DENIED",
                      "type": "string"
                    },
                    "error": {
                      "example": "Access denied",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Access denied - invoice belongs to different user"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get sales invoice by ID",
        "tags": [
          "Sales Invoices"
        ]
      },
      "put": {
        "description": "Update an existing sales invoice with new information.\n\n## Path Parameters\n- **invoice_id**: UUID of the invoice to update\n\n## Request Body\nAll fields are optional for updates:\n- Invoice header fields (dates, numbers, client)\n- Project information and periods\n- Financial amounts and calculations\n- Line items and pricing\n- Payment information and notes\n\n## Update Behavior\n- Only provided fields are updated\n- Omitted fields remain unchanged\n- Line items are replaced entirely if provided\n- Financial totals are recalculated if items change\n\n## Validation\n- Dates must be valid Unix timestamps\n- Financial amounts must be non-negative\n- Client must exist and belong to user\n- Invoice must exist and belong to user\n\n## Security\nOnly allows updates to invoices belonging to the authenticated user.\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the invoice to update",
            "in": "path",
            "name": "invoice_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateSalesInvoiceRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SalesInvoiceResponse"
                }
              }
            },
            "description": "Sales invoice updated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "ACCESS_DENIED",
                      "type": "string"
                    },
                    "error": {
                      "example": "Access denied",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Access denied - invoice belongs to different user"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update an existing sales invoice",
        "tags": [
          "Sales Invoices"
        ]
      }
    },
    "/sales-invoices/{invoice_id}/generate-journal": {
      "post": {
        "description": "Generate an accounting journal entry from a sales invoice for integration with accounting systems.\n\n## Path Parameters\n- **invoice_id**: UUID of the invoice to generate journal entry from\n\n## Journal Entry Generation\nThis endpoint:\n- Creates double-entry accounting records\n- Debits accounts receivable\n- Credits revenue accounts\n- Handles tax accounting entries\n- Links journal to source invoice\n\n## Accounting Rules\nThe generated journal entry follows standard accounting principles:\n- **Debit**: Accounts Receivable (total amount)\n- **Credit**: Revenue (subtotal amount)\n- **Credit**: Tax Payable (tax amount)\n- All entries are balanced and validated\n\n## Journal Entry Structure\nGenerated entries include:\n- Reference to source invoice\n- Client information for receivables\n- Proper account classifications\n- Transaction dates and descriptions\n- Audit trail and timestamps\n\n## Integration Points\nJournal entries can be:\n- Exported to external accounting systems\n- Used for financial reporting\n- Integrated with general ledger\n- Processed for tax reporting\n\n## Error Handling\nCommon generation errors:\n- Invoice not found or inaccessible\n- Missing accounting configuration\n- Invalid financial amounts\n- Duplicate journal entry prevention\n\n## Use Cases\n- Accounting system integration\n- Financial reporting automation\n- General ledger maintenance\n- Tax compliance and reporting\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "UUID of the invoice to generate journal entry from",
            "in": "path",
            "name": "invoice_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/JournalGenerationResponse"
                }
              }
            },
            "description": "Journal entry generated successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "GENERATION_ERROR",
                      "type": "string"
                    },
                    "error": {
                      "example": "Journal generation failed",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Journal generation failed or invalid invoice"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "ACCESS_DENIED",
                      "type": "string"
                    },
                    "error": {
                      "example": "Access denied",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Access denied - invoice belongs to different user"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "DUPLICATE_JOURNAL",
                      "type": "string"
                    },
                    "error": {
                      "example": "Journal entry already exists",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Journal entry already exists for this invoice"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Generate journal entry from invoice",
        "tags": [
          "Sales Invoices"
        ]
      }
    },
    "/sales/workflow/{document_id}": {
      "get": {
        "description": "Retrieve the full sales document workflow chain (見積書→発注書→納品書→請求書) for a given document.\n\n## What's Included\n- Current document details and workflow stage\n- Full chain map (quotation, order, delivery, invoice)\n- Relationship links between chain documents\n- Available workflow actions (create next document, generate journal)\n- Sales invoice details (number, dates, amounts, payment status)\n\n## Workflow Stages\n| Stage | Index | Document Type | Japanese |\n|-------|-------|--------------|----------|\n| quotation | 0 | sales_quotation | 見積書 |\n| order | 1 | purchase_order | 発注書 |\n| delivery | 2 | delivery_note | 納品書 |\n| invoice | 3 | sales_invoice | 請求書 |",
        "parameters": [
          {
            "description": "UUID of any document in the sales workflow chain",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SalesWorkflowResponse"
                }
              }
            },
            "description": "Sales workflow retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Document not found or access denied"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get sales workflow chain for a document",
        "tags": [
          "Sales Workflow"
        ]
      }
    },
    "/search": {
      "get": {
        "description": "Every word must appear (folded: katakana = hiragana, full/half width and case ignored). An amount query (「1234」「1,234」「¥1,234」) also matches amounts exactly. A 書類 also matches when it contains a matching expense line, so an item finds its 経費精算書.",
        "parameters": [
          {
            "example": "ゴミ袋",
            "in": "query",
            "name": "q",
            "required": true,
            "schema": {
              "maxLength": 100,
              "minLength": 1,
              "type": "string"
            }
          },
          {
            "description": "Comma-separated subset of file, document, expense, bank_transaction, journal_entry, client; omitted = all.",
            "in": "query",
            "name": "types",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "Hits per group.",
            "in": "query",
            "name": "limit",
            "required": false,
            "schema": {
              "default": 6,
              "maximum": 20,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/SearchResponse"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Grouped hits"
          },
          "400": {
            "description": "Validation error (RFC 9457): q missing, empty or over 100 chars; unknown type; bad limit"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Find anything across the caller’s records",
        "tags": [
          "Search"
        ]
      }
    },
    "/sentry-tunnel": {
      "post": {
        "description": "Unauthenticated. Body is a raw Sentry envelope (first line JSON header with `dsn`). CSRF skipped. Rate-limited. Max 100KB.",
        "requestBody": {
          "content": {
            "application/x-sentry-envelope": {
              "schema": {
                "format": "binary",
                "type": "string"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Upstream accepted (empty body)"
          },
          "400": {
            "description": "Envelope rejected (empty, allowlist or parse failure). Empty body."
          },
          "413": {
            "description": "Envelope larger than the tunnel limit. Empty body."
          },
          "429": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SentryTunnelError"
                }
              }
            },
            "description": "Rate limited. Two sources: this API's per-client limiter answers with a JSON body; an upstream Sentry 429 is relayed with an EMPTY body plus the backoff headers below, which the browser SDK reads.",
            "headers": {
              "Retry-After": {
                "description": "Seconds to wait before retrying (relayed from Sentry, or set by the limiter).",
                "schema": {
                  "type": "string"
                }
              },
              "X-Sentry-Rate-Limits": {
                "description": "Relayed from Sentry when it rate-limits a data category. Absent on the limiter's own 429.",
                "schema": {
                  "type": "string"
                }
              }
            }
          },
          "502": {
            "description": "Upstream Sentry ingest unreachable"
          }
        },
        "security": [],
        "summary": "Forward a browser Sentry envelope to allowlisted ingest",
        "tags": [
          "Sentry Tunnel"
        ]
      }
    },
    "/shataku/calculations/preview": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/PreviewCalculationRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Calculation preview result"
          },
          "400": {
            "description": "Validation error"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Preview 賃貸料相当額 without persisting",
        "tags": [
          "Shataku"
        ]
      }
    },
    "/shataku/fixed-asset-records/{record_id}/verify": {
      "put": {
        "parameters": [
          {
            "in": "path",
            "name": "record_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Verified"
          },
          "400": {
            "description": "Validation error"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Human-verify OCR values for 課税明細書",
        "tags": [
          "Shataku"
        ]
      }
    },
    "/shataku/properties": {
      "get": {
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "items": {
                        "$ref": "#/components/schemas/ShatakuProperty"
                      },
                      "type": "array"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "OK"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List registered properties",
        "tags": [
          "Shataku"
        ]
      },
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreatePropertyRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "description": "Property created"
          },
          "400": {
            "description": "Validation error"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Register a new property",
        "tags": [
          "Shataku"
        ]
      }
    },
    "/shataku/properties/{property_id}": {
      "delete": {
        "parameters": [
          {
            "in": "path",
            "name": "property_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "204": {
            "description": "Deleted"
          },
          "404": {
            "description": "Not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Delete property",
        "tags": [
          "Shataku"
        ]
      },
      "get": {
        "parameters": [
          {
            "in": "path",
            "name": "property_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK"
          },
          "404": {
            "description": "Not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get property detail",
        "tags": [
          "Shataku"
        ]
      },
      "put": {
        "parameters": [
          {
            "in": "path",
            "name": "property_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreatePropertyRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Updated"
          },
          "404": {
            "description": "Not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update property",
        "tags": [
          "Shataku"
        ]
      }
    },
    "/shataku/properties/{property_id}/calculations": {
      "get": {
        "parameters": [
          {
            "in": "path",
            "name": "property_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List saved rent-equivalent calculations",
        "tags": [
          "Shataku"
        ]
      },
      "post": {
        "parameters": [
          {
            "in": "path",
            "name": "property_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "201": {
            "description": "Snapshot saved"
          },
          "409": {
            "description": "Verification gate not passed"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Persist immutable calculation snapshot",
        "tags": [
          "Shataku"
        ]
      }
    },
    "/shataku/properties/{property_id}/charges": {
      "get": {
        "parameters": [
          {
            "in": "path",
            "name": "property_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List monthly charge schedule",
        "tags": [
          "Shataku"
        ]
      },
      "post": {
        "parameters": [
          {
            "in": "path",
            "name": "property_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "201": {
            "description": "Charges scheduled"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Schedule monthly charges",
        "tags": [
          "Shataku"
        ]
      }
    },
    "/shataku/properties/{property_id}/charges/{charge_id}/journal": {
      "post": {
        "description": "Creates one idempotent journal entry for the charge: Cr 受取家賃（社宅使用料・非課税, tax_code=3 / non_taxable), Dr by collection method (bank_transfer→普通預金, payslip_deduction→役員報酬, receivable/uncollected→未収入金). Returns the existing entry if already posted.",
        "parameters": [
          {
            "in": "path",
            "name": "property_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "in": "path",
            "name": "charge_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "201": {
            "description": "Journal entry created (or existing returned)"
          },
          "404": {
            "description": "Charge not found"
          },
          "422": {
            "description": "Charge amount is zero"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Post a monthly charge to the GL as 受取家賃（社宅使用料・非課税）",
        "tags": [
          "Shataku"
        ]
      }
    },
    "/shataku/properties/{property_id}/documents": {
      "get": {
        "parameters": [
          {
            "in": "path",
            "name": "property_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List generated 規程 / 計算書 documents",
        "tags": [
          "Shataku"
        ]
      },
      "post": {
        "parameters": [
          {
            "in": "path",
            "name": "property_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "201": {
            "description": "Documents generated"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Generate 社宅規程・計算書 documents",
        "tags": [
          "Shataku"
        ]
      }
    },
    "/shataku/properties/{property_id}/fixed-asset-records/upload": {
      "post": {
        "parameters": [
          {
            "in": "path",
            "name": "property_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "multipart/form-data": {
              "schema": {
                "properties": {
                  "file": {
                    "format": "binary",
                    "type": "string"
                  }
                },
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "description": "Record created, OCR queued"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Upload 課税明細書 PDF for OCR",
        "tags": [
          "Shataku"
        ]
      }
    },
    "/shataku/properties/{property_id}/rent-payments": {
      "get": {
        "parameters": [
          {
            "in": "path",
            "name": "property_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List company→landlord rent payments",
        "tags": [
          "Shataku"
        ]
      },
      "post": {
        "parameters": [
          {
            "in": "path",
            "name": "property_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "201": {
            "description": "Payment recorded"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Record a rent payment to landlord",
        "tags": [
          "Shataku"
        ]
      }
    },
    "/shataku/rent-payments/{payment_id}/reconcile": {
      "patch": {
        "parameters": [
          {
            "in": "path",
            "name": "payment_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Reconciled"
          },
          "404": {
            "description": "Payment or transaction not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Link rent payment to a bank-statement transaction",
        "tags": [
          "Shataku"
        ]
      }
    },
    "/signatures": {
      "get": {
        "description": "Retrieve all active signatures for the authenticated user with signed URLs.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "items": {
                        "$ref": "#/components/schemas/Signature"
                      },
                      "type": "array"
                    },
                    "message": {
                      "example": "Success",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Signatures retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get all user signatures",
        "tags": [
          "Signature"
        ]
      }
    },
    "/signatures/default": {
      "get": {
        "description": "Get the overall default signature for the user.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/Signature"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Default signature retrieved"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get default signature",
        "tags": [
          "Signature"
        ]
      }
    },
    "/signatures/default/{signature_type}": {
      "get": {
        "description": "Get the default signature for a specific type.",
        "parameters": [
          {
            "description": "Signature type",
            "in": "path",
            "name": "signature_type",
            "required": true,
            "schema": {
              "enum": [
                "handwritten",
                "digital",
                "initials"
              ],
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/Signature"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Default signature retrieved"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get default signature by type",
        "tags": [
          "Signature"
        ]
      }
    },
    "/signatures/document": {
      "get": {
        "description": "Get default signature URLs formatted for use in document generation templates.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/SignaturesForDocument"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Signature URLs retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get signatures for document templates",
        "tags": [
          "Signature"
        ]
      }
    },
    "/signatures/history": {
      "get": {
        "description": "Get full audit trail for all signatures (compliance feature).",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "history": {
                          "items": {
                            "properties": {
                              "action": {
                                "type": "string"
                              },
                              "changed_at": {
                                "format": "date-time",
                                "type": "string"
                              },
                              "data_after": {
                                "type": "object"
                              },
                              "data_before": {
                                "nullable": true,
                                "type": "object"
                              },
                              "reason": {
                                "nullable": true,
                                "type": "string"
                              },
                              "version": {
                                "type": "integer"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "History retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get signature change history",
        "tags": [
          "Signature"
        ]
      }
    },
    "/signatures/history/{signature_id}": {
      "get": {
        "description": "Get audit trail for a specific signature.",
        "parameters": [
          {
            "description": "Signature UUID",
            "in": "path",
            "name": "signature_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "history": {
                          "items": {
                            "type": "object"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "History retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get specific signature history",
        "tags": [
          "Signature"
        ]
      }
    },
    "/signatures/{signature_id}": {
      "delete": {
        "description": "Soft delete a signature (file preserved for compliance).",
        "parameters": [
          {
            "description": "Signature UUID",
            "in": "path",
            "name": "signature_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "reason": {
                    "description": "Reason for deletion (for audit trail)",
                    "type": "string"
                  }
                },
                "type": "object"
              }
            }
          }
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "message": {
                      "example": "Signature deleted successfully",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Signature deleted successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Delete signature",
        "tags": [
          "Signature"
        ]
      },
      "put": {
        "description": "Update signature name, description, or set as default.",
        "parameters": [
          {
            "description": "Signature UUID",
            "in": "path",
            "name": "signature_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/SignatureUpdateRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/Signature"
                    },
                    "message": {
                      "example": "Signature updated successfully",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Signature updated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update signature details",
        "tags": [
          "Signature"
        ]
      }
    },
    "/signatures/{signature_id}/default": {
      "put": {
        "description": "Set a specific signature as the default for its type.",
        "parameters": [
          {
            "description": "Signature UUID",
            "in": "path",
            "name": "signature_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/Signature"
                    },
                    "message": {
                      "example": "Signature set as default successfully",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Signature set as default successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Set signature as default",
        "tags": [
          "Signature"
        ]
      }
    },
    "/signatures/{signature_type}": {
      "get": {
        "description": "Get all signatures of a specific type.",
        "parameters": [
          {
            "description": "Signature type",
            "in": "path",
            "name": "signature_type",
            "required": true,
            "schema": {
              "enum": [
                "handwritten",
                "digital",
                "initials"
              ],
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "items": {
                        "$ref": "#/components/schemas/Signature"
                      },
                      "type": "array"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Signatures retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get signatures by type",
        "tags": [
          "Signature"
        ]
      },
      "post": {
        "description": "Upload a new signature image.\n\n**Supported Types:**\n- `handwritten` - Scanned or drawn handwritten signature\n- `digital` - Digital/electronic signature\n- `initials` - Abbreviated signature using initials\n\n**File Requirements:**\n- Formats: JPEG, PNG, GIF, WebP, SVG\n- Max size: 1MB\n- Transparent background recommended for PNG/WebP",
        "parameters": [
          {
            "description": "Signature type",
            "in": "path",
            "name": "signature_type",
            "required": true,
            "schema": {
              "enum": [
                "handwritten",
                "digital",
                "initials"
              ],
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "multipart/form-data": {
              "schema": {
                "$ref": "#/components/schemas/SignatureUploadRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/Signature"
                    },
                    "message": {
                      "example": "handwritten signature uploaded successfully",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 201,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Signature uploaded successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Upload signature",
        "tags": [
          "Signature"
        ]
      }
    },
    "/simulation-sessions": {
      "get": {
        "description": "Get a paginated list of simulation sessions for the user.",
        "parameters": [
          {
            "in": "query",
            "name": "page_size",
            "schema": {
              "default": 20,
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "page_number",
            "schema": {
              "default": 1,
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "company_id",
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "include_inactive",
            "schema": {
              "default": false,
              "type": "boolean"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Sessions list retrieved"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List simulation sessions",
        "tags": [
          "Simulation Sessions"
        ]
      },
      "post": {
        "description": "Create a new simulation session.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateSessionRequest"
              }
            }
          }
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SessionResponse"
                }
              }
            },
            "description": "Session created"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create new session",
        "tags": [
          "Simulation Sessions"
        ]
      }
    },
    "/simulation-sessions/current": {
      "get": {
        "description": "Get the current active simulation session for the user. Returns 404 when none exists; a GET never creates one (BL-714) — POST /simulation-sessions creates the first session.",
        "parameters": [
          {
            "description": "Filter by company ID",
            "in": "query",
            "name": "company_id",
            "required": false,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SessionResponse"
                }
              }
            },
            "description": "Current session retrieved"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get current active session",
        "tags": [
          "Simulation Sessions"
        ]
      }
    },
    "/simulation-sessions/{sessionId}": {
      "delete": {
        "parameters": [
          {
            "in": "path",
            "name": "sessionId",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Session deleted"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Delete session (soft delete)",
        "tags": [
          "Simulation Sessions"
        ]
      },
      "get": {
        "parameters": [
          {
            "in": "path",
            "name": "sessionId",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Session retrieved"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get session by ID",
        "tags": [
          "Simulation Sessions"
        ]
      },
      "put": {
        "description": "Update session with optimistic locking. Returns 409 on version conflict.",
        "parameters": [
          {
            "in": "path",
            "name": "sessionId",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateSessionRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Session updated"
          },
          "409": {
            "description": "Version conflict - session modified by another request"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update session (auto-sync)",
        "tags": [
          "Simulation Sessions"
        ]
      }
    },
    "/simulation-sessions/{sessionId}/replay": {
      "post": {
        "description": "Get all transactions for replay/recalculation of financial state.",
        "parameters": [
          {
            "in": "path",
            "name": "sessionId",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Replay data retrieved"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Replay transactions",
        "tags": [
          "Simulation Sessions"
        ]
      }
    },
    "/simulation-sessions/{sessionId}/transactions": {
      "post": {
        "parameters": [
          {
            "in": "path",
            "name": "sessionId",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AddTransactionRequest"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Transaction added"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Add transaction to session",
        "tags": [
          "Simulation Sessions"
        ]
      }
    },
    "/simulation-sessions/{sessionId}/transactions/{transactionId}": {
      "delete": {
        "parameters": [
          {
            "in": "path",
            "name": "sessionId",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "in": "path",
            "name": "transactionId",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Transaction deleted"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Delete transaction",
        "tags": [
          "Simulation Sessions"
        ]
      },
      "patch": {
        "parameters": [
          {
            "in": "path",
            "name": "sessionId",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "in": "path",
            "name": "transactionId",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "isHidden": {
                    "type": "boolean"
                  }
                },
                "type": "object"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Transaction updated"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update transaction (toggle visibility)",
        "tags": [
          "Simulation Sessions"
        ]
      }
    },
    "/simulation-templates": {
      "get": {
        "description": "Get a list of available financial simulation templates.",
        "parameters": [
          {
            "in": "query",
            "name": "page_size",
            "schema": {
              "default": 50,
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "page_number",
            "schema": {
              "default": 1,
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "category",
            "schema": {
              "$ref": "#/components/schemas/SimulationTemplateCategory"
            }
          },
          {
            "in": "query",
            "name": "include_inactive",
            "schema": {
              "default": false,
              "type": "boolean"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Templates list retrieved"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List all templates",
        "tags": [
          "Simulation Templates"
        ]
      }
    },
    "/simulation-templates/{id}": {
      "get": {
        "description": "Get a specific template by UUID or template_id string.",
        "parameters": [
          {
            "description": "Template UUID or template_id (e.g., \"startup-template\")",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/TemplateResponse"
                }
              }
            },
            "description": "Template retrieved"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get template by ID",
        "tags": [
          "Simulation Templates"
        ]
      }
    },
    "/tax-filing/print-bundle": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Print bundle built"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Build a print bundle (PDF pack) for filing forms",
        "tags": [
          "Tax Filing"
        ]
      }
    },
    "/tax-filing/responsible-parties": {
      "get": {
        "parameters": [
          {
            "in": "query",
            "name": "year",
            "required": true,
            "schema": {
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Responsible parties"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List 代表者 / 経理責任者 / 税理士 for company + fiscal year",
        "tags": [
          "Tax Filing"
        ]
      },
      "put": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Parties replaced"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Replace-all responsible parties for company + fiscal year",
        "tags": [
          "Tax Filing"
        ]
      }
    },
    "/tax-filing/session": {
      "get": {
        "parameters": [
          {
            "in": "query",
            "name": "year",
            "required": true,
            "schema": {
              "example": 2025,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Saved session (or empty)"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Load saved tax filing session for resume",
        "tags": [
          "Tax Filing"
        ]
      },
      "put": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Session upserted"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Upsert tax filing hub session (unique on user_id + fiscal_year)",
        "tags": [
          "Tax Filing"
        ]
      }
    },
    "/tax-filing/submitted-returns": {
      "get": {
        "parameters": [
          {
            "in": "query",
            "name": "year",
            "required": true,
            "schema": {
              "example": 2025,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Submitted returns; includes lastDownloadedAt when tax_return_sessions.last_downloaded_at is set"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Filed tax_return_sessions for a year (portal tracker)",
        "tags": [
          "Tax Filing"
        ]
      }
    },
    "/tax-forecast/preview": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/TaxForecastInput"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/TaxForecastResult"
                }
              }
            },
            "description": "Forecast result"
          },
          "400": {
            "description": "Invalid input"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "納税キャッシュフロー予測プレビュー (stateless)",
        "tags": [
          "Tax Forecast"
        ]
      }
    },
    "/tax-forecast/snapshots": {
      "get": {
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                }
              }
            },
            "description": "List of snapshots"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List saved forecast snapshots",
        "tags": [
          "Tax Forecast"
        ]
      },
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "fiscalPeriodEnd": {
                    "format": "date",
                    "type": "string"
                  },
                  "fiscalPeriodStart": {
                    "format": "date",
                    "type": "string"
                  },
                  "inputs": {
                    "$ref": "#/components/schemas/TaxForecastInput"
                  },
                  "result": {
                    "$ref": "#/components/schemas/TaxForecastResult"
                  }
                },
                "required": [
                  "inputs",
                  "result"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "id": {
                          "format": "uuid",
                          "type": "string"
                        }
                      },
                      "type": "object"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Snapshot saved"
          },
          "400": {
            "description": "Invalid input"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Save a forecast snapshot",
        "tags": [
          "Tax Forecast"
        ]
      }
    },
    "/tax-forecast/snapshots/{id}": {
      "get": {
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                }
              }
            },
            "description": "Snapshot detail"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Not found"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get a single forecast snapshot",
        "tags": [
          "Tax Forecast"
        ]
      }
    },
    "/tax-journal/init": {
      "get": {
        "description": "Composite endpoint for the 仕訳帳 page. Every source is read in parallel and fails\nindependently.\n\n**Default (no `include`)** — unchanged since v5.14: unsyncDocuments, signatures, journalEntries,\njournalSummary, accountSummary, and healthCheck when `include_health_check=true`.\n\n**`include` (v5.20+)** — a comma-separated whitelist of the sources to compute, from\n`unsync_count`, `signatures`, `journal_entries`, `journal_summary`, `account_summary`,\n`health_check`, `flat_journal_page`. Only the listed sources are computed and only their keys are\npresent; the others cost no query. Tokens are lower-cased, trimmed and de-duplicated, order does not\nmatter, and an **unknown token is a 400** (Problem Details, `errors[].field = \"query.include\"`) so a typo\ncan never silently drop a panel. When `include` is present it is authoritative and\n`include_health_check` is ignored.\n\nWith `include=unsync_count` the unsync read uses page size 1 and returns `unsyncDocuments: { items: [],\npagination }` — read the count from `pagination.totalItems`.\n\n**Caching:** responses are memoised per user for 120 s, keyed by the date range, paging, status AND the\nnormalised `include` list. A payload containing `flat_journal_page` is neither served from nor written to\nthat cache (journal mutations do not purge these keys, and a stale seeded page would show pre-edit rows).",
        "operationId": "getTaxJournalInit",
        "parameters": [
          {
            "description": "Comma-separated sources to compute. Omit for the default set. Unknown tokens → 400. Example: `unsync_count,journal_summary,flat_journal_page`.",
            "in": "query",
            "name": "include",
            "required": false,
            "schema": {
              "example": "unsync_count,journal_summary",
              "type": "string"
            }
          },
          {
            "description": "Range start, YYYYMMDD. Applies to journalEntries, the summaries and flatJournalPage.",
            "in": "query",
            "name": "start_date",
            "required": false,
            "schema": {
              "example": 20260101,
              "type": "integer"
            }
          },
          {
            "description": "Range end, YYYYMMDD.",
            "in": "query",
            "name": "end_date",
            "required": false,
            "schema": {
              "example": 20261231,
              "type": "integer"
            }
          },
          {
            "description": "Journal status filter, forwarded to journalEntries and flatJournalPage.",
            "in": "query",
            "name": "status",
            "required": false,
            "schema": {
              "example": "posted",
              "type": "string"
            }
          },
          {
            "description": "Page size of the GROUPED journalEntries block (1–100, default 20).",
            "in": "query",
            "name": "page_size",
            "required": false,
            "schema": {
              "default": 20,
              "maximum": 100,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "description": "Page number of the grouped journalEntries block (default 1).",
            "in": "query",
            "name": "page_number",
            "required": false,
            "schema": {
              "default": 1,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "description": "`'true'` adds healthCheck (heavier query). Ignored when `include` is present.",
            "in": "query",
            "name": "include_health_check",
            "required": false,
            "schema": {
              "enum": [
                "true",
                "false"
              ],
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/TaxJournalInitResponse"
                }
              }
            },
            "description": "The requested sources"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get the /tax-journal page data in one request",
        "tags": [
          "Tax Journal"
        ]
      }
    },
    "/tax-journal/invalidate": {
      "post": {
        "description": "Evicts the caller's cached GET /tax-journal/init payloads on the instance that serves the request. Call after journal or signature edits. Other warm instances keep their copy until its TTL (120 s).",
        "operationId": "invalidateTaxJournalCache",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "deleted": {
                          "example": 3,
                          "type": "integer"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Tax-journal cache invalidated",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Cache entries evicted"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Invalidate the tax-journal cache for the current user",
        "tags": [
          "Tax Journal"
        ]
      }
    },
    "/tax-payment-matches": {
      "get": {
        "description": "Unique matches only: amount exact, inside the payment window of the 納期限, the bank naming the payee (office payments: 「PE 地方税共同機構」). Dismissed pairings are left out.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "items": {
                          "items": {
                            "$ref": "#/components/schemas/TaxPaymentMatch"
                          },
                          "type": "array"
                        }
                      },
                      "required": [
                        "items"
                      ],
                      "type": "object"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Suggestions"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "The caller’s exact bank-feed → tax-payment suggestions",
        "tags": [
          "Tax payment matches"
        ]
      }
    },
    "/tax-payment-matches/confirm": {
      "post": {
        "description": "The suggestions are recomputed; only ids still current are applied. deadline_paid completes the row as 納付済 (the bank date, the withdrawals as evidence); office_payment links the withdrawal and fills paid_on / payment_channel where empty.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/TaxPaymentMatchIdsRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/TaxPaymentMatchWriteResult"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Applied and skipped ids"
          },
          "400": {
            "description": "Validation error (RFC 9457)"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Record the suggestions the owner confirmed",
        "tags": [
          "Tax payment matches"
        ]
      }
    },
    "/tax-payment-matches/dismiss": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/TaxPaymentMatchIdsRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/TaxPaymentMatchWriteResult"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "Dismissed and skipped ids"
          },
          "400": {
            "description": "Validation error (RFC 9457)"
          },
          "401": {
            "description": "Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "「違う」: hide these pairings for good",
        "tags": [
          "Tax payment matches"
        ]
      }
    },
    "/tax/accounting-import/execute": {
      "post": {
        "description": "プレビューと同じ解析をして、エラーのない伝票を1つのトランザクションで登録します（全件成功か全件なし）。対応付けのない勘定科目があれば何も書き込まずに 400。取り込み済みの伝票はスキップします。決算整理仕訳は source_type `adjustment`、開始仕訳は `opening_balance` で登録します。",
        "requestBody": {
          "content": {
            "multipart/form-data": {
              "schema": {
                "properties": {
                  "file": {
                    "description": "CSV / TSV / TXT / .xlsx（4MB まで。Lambda Function URL の 6MB 上限のため）。.xls は 400 で保存し直しを案内します",
                    "format": "binary",
                    "type": "string"
                  },
                  "mappings": {
                    "description": "JSON 配列: [{ externalCode, externalName, sbcAccountId, sbcAccountCode, sbcAccountName }]",
                    "type": "string"
                  },
                  "sourceType": {
                    "description": "インポート元。`auto`（既定）は内容から判別します。選択と内容が食い違う場合は内容を優先し、警告を返します。",
                    "enum": [
                      "yayoi",
                      "freee",
                      "moneyforward",
                      "kaikeioh",
                      "generic",
                      "auto"
                    ],
                    "type": "string"
                  },
                  "text": {
                    "description": "ファイルの代わりに貼り付けたデータ（スプレッドシートのセル範囲 = TSV、または CSV テキスト）",
                    "maxLength": 5000000,
                    "type": "string"
                  }
                },
                "type": "object"
              }
            }
          },
          "description": "file または text のどちらか一方 + mappings",
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AccountingImportResult"
                }
              }
            },
            "description": "取り込み結果"
          },
          "400": {
            "content": {
              "application/problem+json": {
                "schema": {
                  "type": "object"
                }
              }
            },
            "description": "対応付けのない勘定科目・ロック済み期間・形式エラー"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "仕訳データの取り込み（1トランザクション・取り込み済みはスキップ）",
        "tags": [
          "AccountingImport"
        ]
      }
    },
    "/tax/accounting-import/format-spec/{sourceType}": {
      "get": {
        "parameters": [
          {
            "in": "path",
            "name": "sourceType",
            "required": true,
            "schema": {
              "enum": [
                "yayoi",
                "freee",
                "moneyforward",
                "kaikeioh",
                "generic"
              ],
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                }
              }
            },
            "description": "形式の説明"
          },
          "400": {
            "content": {
              "application/problem+json": {
                "schema": {
                  "type": "object"
                }
              }
            },
            "description": "未対応の sourceType"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "インポート元ごとの形式と書き出し手順",
        "tags": [
          "AccountingImport"
        ]
      }
    },
    "/tax/accounting-import/opening-balance/execute": {
      "post": {
        "description": "プレビューで canImport が true のときだけ登録します。登録は POST /journal-entries/opening-balance と同じ処理（貸借一致・期間ロック）を通ります。同じ日付の期首残高がすでにあれば 409。",
        "requestBody": {
          "content": {
            "multipart/form-data": {
              "schema": {
                "properties": {
                  "entryDate": {
                    "description": "YYYYMMDD（期首日の前日）",
                    "type": "integer"
                  },
                  "file": {
                    "description": "CSV / TSV / TXT / .xlsx（4MB まで。Lambda Function URL の 6MB 上限のため）。.xls は 400 で保存し直しを案内します",
                    "format": "binary",
                    "type": "string"
                  },
                  "mappings": {
                    "description": "JSON 配列: [{ externalName, sbcAccountCode }]",
                    "type": "string"
                  },
                  "text": {
                    "description": "ファイルの代わりに貼り付けたデータ（スプレッドシートのセル範囲 = TSV、または CSV テキスト）",
                    "maxLength": 5000000,
                    "type": "string"
                  }
                },
                "type": "object"
              }
            }
          },
          "description": "file または text のどちらか一方",
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/OpeningBalanceImportResult"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "登録した期首残高"
          },
          "400": {
            "content": {
              "application/problem+json": {
                "schema": {
                  "type": "object"
                }
              }
            },
            "description": "貸借不一致・未対応の科目・期首日不明"
          },
          "401": {
            "content": {
              "application/problem+json": {
                "schema": {
                  "type": "object"
                }
              }
            },
            "description": "未認証"
          },
          "409": {
            "content": {
              "application/problem+json": {
                "schema": {
                  "type": "object"
                }
              }
            },
            "description": "同じ日付の期首残高がすでにある"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "期首残高ファイルの登録",
        "tags": [
          "AccountingImport"
        ]
      }
    },
    "/tax/accounting-import/opening-balance/preview": {
      "post": {
        "description": "freee の `勘定科目,借方残高,貸方残高`、弥生の6列（期首日・勘定科目名・貸借区分・補助科目名・部門・前期繰越残高）、または見出し付きの汎用 CSV / TSV / .xlsx / 貼り付けを読みます。補助科目・部門は勘定科目ごとに合計します。借方合計と貸方合計が一致しないとき、ファイルに繰越利益剰余金がなければ差額を繰越利益剰余金として `plug` に示します。",
        "requestBody": {
          "content": {
            "multipart/form-data": {
              "schema": {
                "properties": {
                  "entryDate": {
                    "description": "YYYYMMDD（期首日の前日）。省略時は弥生ファイルの期首日から求めます",
                    "type": "integer"
                  },
                  "file": {
                    "description": "CSV / TSV / TXT / .xlsx（4MB まで。Lambda Function URL の 6MB 上限のため）。.xls は 400 で保存し直しを案内します",
                    "format": "binary",
                    "type": "string"
                  },
                  "mappings": {
                    "description": "JSON 配列: [{ externalName, sbcAccountCode }]",
                    "type": "string"
                  },
                  "text": {
                    "description": "ファイルの代わりに貼り付けたデータ（スプレッドシートのセル範囲 = TSV、または CSV テキスト）",
                    "maxLength": 5000000,
                    "type": "string"
                  }
                },
                "type": "object"
              }
            }
          },
          "description": "file または text のどちらか一方",
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/OpeningBalanceImportPreview"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "required": [
                    "success",
                    "data"
                  ],
                  "type": "object"
                }
              }
            },
            "description": "プレビュー"
          },
          "400": {
            "content": {
              "application/problem+json": {
                "schema": {
                  "type": "object"
                }
              }
            },
            "description": "列が見つからない・空のデータ"
          },
          "401": {
            "content": {
              "application/problem+json": {
                "schema": {
                  "type": "object"
                }
              }
            },
            "description": "未認証"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "期首残高ファイルのプレビュー（freee 開始残高・弥生 期首残高・汎用）",
        "tags": [
          "AccountingImport"
        ]
      }
    },
    "/tax/accounting-import/preview": {
      "post": {
        "description": "ファイル（`file`）か貼り付け（`text`）のどちらかを送ります。伝票単位で複合仕訳にまとめ、貸借が合わない伝票はエラー（取り込まない）。同じ内容の仕訳がすでに取り込まれていれば `alreadyImportedCount` に数えます。何も書き込みません。",
        "requestBody": {
          "content": {
            "multipart/form-data": {
              "schema": {
                "properties": {
                  "file": {
                    "description": "CSV / TSV / TXT / .xlsx（4MB まで。Lambda Function URL の 6MB 上限のため）。.xls は 400 で保存し直しを案内します",
                    "format": "binary",
                    "type": "string"
                  },
                  "mappings": {
                    "description": "JSON 配列: [{ externalCode, externalName, sbcAccountId, sbcAccountCode, sbcAccountName }]",
                    "type": "string"
                  },
                  "sourceType": {
                    "description": "インポート元。`auto`（既定）は内容から判別します。選択と内容が食い違う場合は内容を優先し、警告を返します。",
                    "enum": [
                      "yayoi",
                      "freee",
                      "moneyforward",
                      "kaikeioh",
                      "generic",
                      "auto"
                    ],
                    "type": "string"
                  },
                  "text": {
                    "description": "ファイルの代わりに貼り付けたデータ（スプレッドシートのセル範囲 = TSV、または CSV テキスト）",
                    "maxLength": 5000000,
                    "type": "string"
                  }
                },
                "type": "object"
              }
            }
          },
          "description": "file または text のどちらか一方",
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AccountingImportPreview"
                }
              }
            },
            "description": "プレビュー"
          },
          "400": {
            "content": {
              "application/problem+json": {
                "schema": {
                  "type": "object"
                }
              }
            },
            "description": "空のデータ・.xls・形式エラー"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "仕訳データの取込プレビュー（複合仕訳ごとの貸借・取り込み済み件数）",
        "tags": [
          "AccountingImport"
        ]
      }
    },
    "/tax/accounting-import/suggest-mappings": {
      "post": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "externalAccounts": {
                    "items": {
                      "properties": {
                        "code": {
                          "type": "string"
                        },
                        "name": {
                          "type": "string"
                        }
                      },
                      "type": "object"
                    },
                    "type": "array"
                  }
                },
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "items": {
                    "type": "object"
                  },
                  "type": "array"
                }
              }
            },
            "description": "推定結果"
          },
          "400": {
            "content": {
              "application/problem+json": {
                "schema": {
                  "type": "object"
                }
              }
            },
            "description": "externalAccounts がない"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "外部の勘定科目名から一人社長の科目を推定",
        "tags": [
          "AccountingImport"
        ]
      }
    },
    "/tax/beppyo-overrides": {
      "delete": {
        "parameters": [
          {
            "in": "query",
            "name": "year",
            "required": true,
            "schema": {
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "form_key",
            "required": true,
            "schema": {
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "cell_key",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Override deleted"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Delete a 別表 per-cell override",
        "tags": [
          "Tax Compliance"
        ]
      },
      "get": {
        "parameters": [
          {
            "in": "query",
            "name": "year",
            "required": true,
            "schema": {
              "example": 2025,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Override list"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List 別表 per-cell overrides for a fiscal year",
        "tags": [
          "Tax Compliance"
        ]
      },
      "put": {
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Override upserted"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Upsert a 別表 per-cell override",
        "tags": [
          "Tax Compliance"
        ]
      }
    },
    "/tax/deductions/current": {
      "get": {
        "description": "Get the current year's tax deduction configuration.\n\n## Deduction Config (v4.43)\nReturns all deduction rules for the specified year:\n- **基礎控除**: Basic personal deduction (max ¥950,000 for 令和7年)\n- **給与所得控除**: Employment income deduction (min ¥650,000)\n- **扶養控除**: Dependent deduction (income limit ¥580,000)\n- **配偶者控除**: Spouse deduction\n\n## 令和7年度税制改正 Changes\n- 基礎控除: ¥480,000 → ¥950,000 (所得≤132万)\n- 給与所得控除: 最低保障 ¥550,000 → ¥650,000\n- 扶養親族所得要件: ¥480,000 → ¥580,000",
        "parameters": [
          {
            "description": "Tax year (defaults to current year)",
            "in": "query",
            "name": "year",
            "required": false,
            "schema": {
              "example": "2025",
              "pattern": "^\\d{4}$",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/DeductionConfig"
                    },
                    "message": {
                      "example": "令和7年分の控除設定を取得しました",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Deduction config retrieved"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "message": {
                      "example": "控除設定が見つかりません: 2027年",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Deduction config not found for specified year"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get current deduction config (控除設定取得)",
        "tags": [
          "Tax Compliance"
        ]
      }
    },
    "/tax/estimate": {
      "post": {
        "description": "Estimate corporate and consumption tax based on revenue, expenses, and company details.\n\n## Corporate Tax Estimation\nUses progressive rates from the tax_rate_schedules table:\n- SME reduced rate for income ≤ ¥8M (capital ≤ ¥100M)\n- Standard rate for income > ¥8M or large corporations\n- Includes local corporate tax (地方法人税)\n\n## Consumption Tax Estimation\nSupports multiple calculation methods:\n- `standard`: Standard method (原則課税)\n- `simplified`: Simplified method (簡易課税) with deemed purchase rates by industry\n- `two_percent`: 2% special provisions for invoice system transition\n\n## Important\nThis is an **estimation** for planning purposes only.\nActual tax filing should use professional tax software or a certified tax accountant.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "capital": {
                    "default": 10000000,
                    "description": "Company capital in JPY",
                    "example": 10000000,
                    "minimum": 0,
                    "type": "number"
                  },
                  "consumption_tax_method": {
                    "default": "standard",
                    "description": "Consumption tax calculation method",
                    "enum": [
                      "standard",
                      "simplified",
                      "two_percent"
                    ],
                    "type": "string"
                  },
                  "expenses": {
                    "description": "Annual expenses in JPY",
                    "example": 20000000,
                    "minimum": 0,
                    "type": "number"
                  },
                  "revenue": {
                    "description": "Annual revenue in JPY",
                    "example": 30000000,
                    "minimum": 0,
                    "type": "number"
                  },
                  "simplified_industry_type": {
                    "description": "Industry type for simplified method (1-6)",
                    "example": 5,
                    "maximum": 6,
                    "minimum": 1,
                    "type": "integer"
                  }
                },
                "required": [
                  "revenue",
                  "expenses"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "consumption_tax": {
                          "properties": {
                            "input_tax_credit": {
                              "type": "number"
                            },
                            "method": {
                              "type": "string"
                            },
                            "net_tax": {
                              "type": "number"
                            },
                            "tax_amount": {
                              "type": "number"
                            }
                          },
                          "type": "object"
                        },
                        "corporate_tax": {
                          "properties": {
                            "effective_rate": {
                              "type": "number"
                            },
                            "local_corporate_tax": {
                              "type": "number"
                            },
                            "tax_amount": {
                              "type": "number"
                            },
                            "taxable_income": {
                              "type": "number"
                            },
                            "total": {
                              "type": "number"
                            }
                          },
                          "type": "object"
                        },
                        "disclaimer": {
                          "type": "string"
                        },
                        "total_estimated_tax": {
                          "type": "number"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "税金概算を計算しました",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Tax estimation calculated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Estimate corporate & consumption tax (法人税・消費税概算)",
        "tags": [
          "Tax Compliance"
        ]
      }
    },
    "/tax/fiscal-periods": {
      "get": {
        "description": "Retrieve all fiscal periods for Japanese tax compliance management.\n\n## Fiscal Period Management (会計期間管理)\nComprehensive fiscal period management with:\n- **Period Listing**: View all fiscal periods with status information\n- **Status Tracking**: Monitor period status (open, closing, closed, audited)\n- **Statistics**: Get quick statistics on period status distribution\n- **Filtering**: Filter by fiscal year and status\n- **Japanese Standards**: Full compliance with Japanese accounting periods\n\n## Period Status Workflow\n- **Open (開始)**: Active period accepting transactions\n- **Closing (締切中)**: Period in closing process with validation\n- **Closed (締切済)**: Period closed, no new transactions allowed\n- **Audited (監査済)**: Period has been audited and finalized\n\n## Use Cases\n- **Period Overview**: Get overview of all accounting periods\n- **Status Monitoring**: Monitor period close status and progress\n- **Compliance Tracking**: Track compliance with Japanese accounting standards\n- **Audit Preparation**: Prepare periods for audit and review\n- **Management Reporting**: Provide period status for management review\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Filter by fiscal year",
            "in": "query",
            "name": "fiscalYear",
            "required": false,
            "schema": {
              "example": 2024,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FiscalPeriodListResponse"
                }
              }
            },
            "description": "Fiscal periods retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List fiscal periods (会計期間一覧)",
        "tags": [
          "Tax Compliance"
        ]
      },
      "post": {
        "description": "Create a new fiscal period for Japanese accounting compliance.\n\n## Fiscal Period Creation\nCreate new accounting periods with:\n- **Period Definition**: Define period name, dates, and type\n- **Validation**: Validate period dates and prevent overlaps\n- **Status Management**: Initialize period with open status\n- **Japanese Standards**: Comply with Japanese fiscal year standards\n- **Audit Trail**: Complete audit trail for period creation\n\n## Period Types\n- **ANNUAL**: Full fiscal year period (年次)\n- **QUARTERLY**: Quarterly period (四半期)\n- **MONTHLY**: Monthly period (月次)\n\n## Validation Rules\n- Start date must be before end date\n- Period cannot overlap with existing periods\n- Period name must be unique within fiscal year\n- Dates must follow YYYYMMDD format\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateFiscalPeriodRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FiscalPeriodResponse"
                }
              }
            },
            "description": "Fiscal period created successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create fiscal period (会計期間作成)",
        "tags": [
          "Tax Compliance"
        ]
      }
    },
    "/tax/fiscal-periods/auto-generate": {
      "post": {
        "description": "Automatically generate fiscal periods for a complete fiscal year.\n\n## Auto-Generation Features\nGenerate complete fiscal year with:\n- **Monthly Periods**: Generate 12 monthly periods for detailed tracking\n- **Quarterly Periods**: Generate 4 quarterly periods for summary reporting\n- **Date Validation**: Validate fiscal year start and end dates\n- **Naming Convention**: Apply Japanese naming conventions for periods\n- **Status Initialization**: Initialize all periods with open status\n\n## Generation Options\n- **Monthly Generation**: Create 12 monthly periods (recommended)\n- **Quarterly Generation**: Create 4 quarterly periods\n- **Custom Dates**: Support custom fiscal year dates\n- **Company Association**: Associate periods with specific company\n\n## Validation Rules\n- Fiscal year start must be before end date\n- Fiscal year must span exactly 12 months\n- No overlapping periods allowed\n- Dates must follow YYYYMMDD format\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AutoGenerateFiscalYearRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "fiscalYear": {
                          "example": 2024,
                          "type": "integer"
                        },
                        "periods": {
                          "items": {
                            "$ref": "#/components/schemas/FiscalPeriod"
                          },
                          "type": "array"
                        },
                        "periodsCreated": {
                          "example": 12,
                          "type": "integer"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "Fiscal year periods generated successfully",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 201,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Fiscal year periods generated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Auto-generate fiscal year periods (会計期間自動生成)",
        "tags": [
          "Tax Compliance"
        ]
      }
    },
    "/tax/fiscal-periods/current": {
      "get": {
        "description": "Get the current active fiscal period for transaction processing.\n\n## Current Period Retrieval\nGet active period information with:\n- **Active Period**: Retrieve currently active fiscal period\n- **Status Validation**: Ensure period is open for transactions\n- **Date Validation**: Validate current date falls within period\n- **Transaction Control**: Control transaction posting based on period status\n- **Compliance Check**: Ensure compliance with Japanese accounting standards\n\n## Use Cases\n- **Transaction Validation**: Validate transactions against current period\n- **Period Status Check**: Check if period is open for new transactions\n- **Date Validation**: Ensure transaction dates fall within current period\n- **System Integration**: Integrate with transaction processing systems\n- **Compliance Monitoring**: Monitor current period compliance status\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FiscalPeriodResponse"
                }
              }
            },
            "description": "Current fiscal period retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "CURRENT_PERIOD_NOT_FOUND",
                      "type": "string"
                    },
                    "message": {
                      "example": "No current fiscal period found",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 404,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "No current fiscal period found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get current fiscal period (現在の会計期間)",
        "tags": [
          "Tax Compliance"
        ]
      }
    },
    "/tax/fiscal-periods/{id}": {
      "get": {
        "description": "Get detailed information for a specific fiscal period.\n\n## Period Details\nRetrieve comprehensive period information with:\n- **Period Information**: Complete period details and metadata\n- **Status History**: Track period status changes and audit trail\n- **Validation Results**: View period close validation results\n- **Transaction Summary**: Summary of transactions within the period\n- **Compliance Status**: Current compliance status and requirements\n\n## Use Cases\n- **Period Review**: Review period details and status\n- **Audit Preparation**: Prepare period information for audit\n- **Compliance Check**: Check period compliance status\n- **Transaction Analysis**: Analyze transactions within the period\n- **Status Monitoring**: Monitor period status and changes\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Fiscal period ID",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FiscalPeriodResponse"
                }
              }
            },
            "description": "Fiscal period details retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get fiscal period details (会計期間詳細)",
        "tags": [
          "Tax Compliance"
        ]
      }
    },
    "/tax/fiscal-periods/{id}/close": {
      "patch": {
        "description": "Close a fiscal period after validation and compliance checks.\n\n## Period Close Process\nComprehensive period close with:\n- **Pre-Close Validation**: Validate all transactions and reconciliations\n- **Business Rules**: Apply Japanese accounting business rules\n- **Compliance Check**: Ensure compliance with tax regulations\n- **Audit Trail**: Complete audit trail for period close\n- **Lock Controls**: Implement posting lockout after close\n\n## Validation Checks\n- **Bank Reconciliation**: All bank transactions must be reconciled\n- **Journal Evidence**: All journal entries must have supporting evidence\n- **Suspense Accounts**: Suspense account balances must be resolved\n- **Expense Reports**: All expense reports must be processed\n- **Tax Compliance**: All tax obligations must be met\n\n## Close Workflow\n1. **Pre-validation**: Check all business rules and requirements\n2. **Warning Review**: Review and acknowledge warnings\n3. **Final Close**: Execute period close with audit trail\n4. **Lock Enforcement**: Prevent new transactions in closed period\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Fiscal period ID to close",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/TaxComplianceActionResponse"
                }
              }
            },
            "description": "Fiscal period closed successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/FiscalPeriodCloseValidation"
                    },
                    "message": {
                      "example": "Period cannot be closed",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 400,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Period cannot be closed due to validation issues"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Close fiscal period (会計期間締切)",
        "tags": [
          "Tax Compliance"
        ]
      }
    },
    "/tax/fiscal-periods/{id}/lock": {
      "patch": {
        "description": "Lock posting to a fiscal period to prevent new transactions.\n\n## Posting Lock Controls\nImplement strict posting controls with:\n- **Transaction Prevention**: Prevent new transactions in locked period\n- **Audit Protection**: Protect period data during audit process\n- **Compliance Enforcement**: Enforce Japanese accounting standards\n- **User Notifications**: Notify users of posting restrictions\n- **Override Controls**: Administrative override capabilities\n\n## Lock Features\n- **Immediate Effect**: Lock takes effect immediately\n- **Transaction Blocking**: Block all new transaction posting\n- **Audit Trail**: Complete audit trail for lock actions\n- **Status Tracking**: Track lock status and history\n- **Administrative Control**: Administrative unlock capabilities\n\n## Use Cases\n- **Audit Preparation**: Lock period during audit preparation\n- **Compliance Enforcement**: Enforce period close compliance\n- **Data Protection**: Protect period data from changes\n- **Regulatory Compliance**: Meet regulatory reporting requirements\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Fiscal period ID to lock",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/TaxComplianceActionResponse"
                }
              }
            },
            "description": "Fiscal period locked successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Lock fiscal period posting (会計期間ロック)",
        "tags": [
          "Tax Compliance"
        ]
      }
    },
    "/tax/fiscal-periods/{id}/reopen": {
      "patch": {
        "description": "Reopen a closed fiscal period with proper justification and audit trail.\n\n## Period Reopen Process\nControlled period reopening with:\n- **Justification Required**: Mandatory reason for reopening\n- **Audit Trail**: Complete audit trail for reopen action\n- **Status Restoration**: Restore period to open status\n- **Notification System**: Notify stakeholders of reopen action\n- **Compliance Tracking**: Track compliance implications\n\n## Reopen Requirements\n- **Valid Reason**: Must provide valid business reason\n- **Authorization**: Appropriate user authorization required\n- **Audit Documentation**: Document reason for audit purposes\n- **Stakeholder Notification**: Notify relevant stakeholders\n- **Compliance Review**: Review compliance implications\n\n## Common Reopen Reasons\n- Additional adjustments required for year-end audit\n- Correction of material errors discovered after close\n- Regulatory requirement for additional entries\n- Court order or legal requirement for adjustments\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Fiscal period ID to reopen",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ReopenPeriodRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/TaxComplianceActionResponse"
                }
              }
            },
            "description": "Fiscal period reopened successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Reopen fiscal period (会計期間再開)",
        "tags": [
          "Tax Compliance"
        ]
      }
    },
    "/tax/withholding": {
      "get": {
        "description": "Retrieve withholding tax records for Japanese tax compliance.\n\n## Withholding Tax Management (源泉徴収管理)\nComprehensive withholding tax tracking with:\n- **Payment Records**: Track all withholding tax payments\n- **Rate Calculations**: Automatic Japanese withholding rate calculations\n- **Payee Management**: Manage individual and corporate payees\n- **Category Tracking**: Track payments by category (salary, freelance, etc.)\n- **Compliance Monitoring**: Monitor compliance with Japanese tax law\n\n## Japanese Withholding Rates\n- **Under ¥1,000,000**: 10.21% withholding rate\n- **Over ¥1,000,000**: 20.42% withholding rate\n- **Custom Rates**: Support for special withholding rates\n\n## Payment Categories\n- **Salary (給与)**: Regular salary payments\n- **Bonus (賞与)**: Bonus and incentive payments\n- **Retirement (退職金)**: Retirement payments\n- **Freelance Fee (報酬)**: Freelance and contractor payments\n- **Royalty (著作権料)**: Royalty and licensing payments\n- **Prize (賞金)**: Prize and award payments\n- **Other (その他)**: Other withholding tax payments\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Filter by payment year",
            "in": "query",
            "name": "year",
            "required": false,
            "schema": {
              "example": 2024,
              "type": "integer"
            }
          },
          {
            "description": "Filter by payment month",
            "in": "query",
            "name": "month",
            "required": false,
            "schema": {
              "example": 3,
              "maximum": 12,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "description": "Filter by payment category",
            "in": "query",
            "name": "category",
            "required": false,
            "schema": {
              "$ref": "#/components/schemas/WithholdingCategory"
            }
          },
          {
            "description": "Filter by payee type",
            "in": "query",
            "name": "payee_type",
            "required": false,
            "schema": {
              "$ref": "#/components/schemas/PayeeType"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/WithholdingTaxListResponse"
                }
              }
            },
            "description": "Withholding taxes retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List withholding taxes (源泉徴収一覧)",
        "tags": [
          "Tax Compliance"
        ]
      },
      "post": {
        "description": "Create a new withholding tax record with automatic calculations.\n\n## Withholding Tax Creation\nCreate withholding tax records with:\n- **Automatic Calculations**: Automatic withholding amount calculations\n- **Rate Determination**: Automatic rate determination based on amount\n- **Payee Management**: Comprehensive payee information management\n- **Category Classification**: Proper category classification for tax purposes\n- **Compliance Validation**: Validation against Japanese tax requirements\n\n## Calculation Rules\n- **10.21% Rate**: Applied to payments under ¥1,000,000\n- **20.42% Rate**: Applied to payments over ¥1,000,000\n- **Custom Rates**: Support for special withholding rates\n- **Net Amount**: Automatic net amount calculation (gross - withholding)\n\n## Payee Information\n- **Individual Payees**: Full name and address information\n- **Corporate Payees**: Company name and business address\n- **My Number**: Optional My Number (マイナンバー) tracking\n- **Address Management**: Complete address information for tax reporting\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateWithholdingTaxRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/WithholdingTaxResponse"
                }
              }
            },
            "description": "Withholding tax record created successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create withholding tax record (源泉徴収作成)",
        "tags": [
          "Tax Compliance"
        ]
      }
    },
    "/tax/withholding-slip/{document_id}/source-documents": {
      "get": {
        "description": "Retrieve salary slips and payment statements linked to a 源泉徴収票 (tax withholding slip) document.\n\nUsed by the frontend withholding-tax dock to display related documents.\n\n## Resolution Logic\n1. Reads payeeName and fiscalYear from the slip's content\n2. Queries withholding_taxes for matching records (same payee + year)\n3. Includes source_document relation for payment statements\n4. Queries salary_slip documents matching the same payee + period\n\n## Response\nReturns three arrays: salary slips, payment statements, and raw withholding records, plus a summary with totals.",
        "parameters": [
          {
            "description": "The tax_withholding_slip document ID",
            "in": "path",
            "name": "document_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/WithholdingSlipSourceDocuments"
                    },
                    "message": {
                      "example": "源泉徴収票の関連書類を取得しました",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Source documents retrieved"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "message": {
                      "example": "源泉徴収票が見つかりません",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Document not found or not a tax_withholding_slip type"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get withholding slip source documents (源泉徴収票の関連書類)",
        "tags": [
          "Tax Compliance"
        ]
      }
    },
    "/tax/withholding/by-payee/{payeeName}": {
      "get": {
        "description": "Get all withholding tax records for a specific payee.\n\n## Payee-Specific Records\nDetailed payee records with:\n- **Complete History**: All withholding tax records for the payee\n- **Payment Timeline**: Chronological payment history\n- **Category Analysis**: Breakdown by payment category\n- **Annual Summaries**: Annual totals and summaries\n- **Tax Slip Data**: Data for withholding tax slip generation\n\n## Record Information\n- **Payment Details**: Complete payment and withholding details\n- **Category Classification**: Payment category classification\n- **Date Range**: Flexible date range filtering\n- **Status Tracking**: Payment and compliance status tracking\n- **Historical Analysis**: Historical payment analysis\n\n## Use Cases\n- **Payee Analysis**: Analyze payments to specific payee\n- **Tax Slip Preparation**: Prepare data for individual tax slips\n- **Payment History**: Review complete payment history\n- **Compliance Review**: Review compliance for specific payee\n- **Audit Support**: Support audit review of payee payments\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Name of the payee",
            "in": "path",
            "name": "payeeName",
            "required": true,
            "schema": {
              "example": "田中太郎",
              "type": "string"
            }
          },
          {
            "description": "Filter by year",
            "in": "query",
            "name": "year",
            "required": false,
            "schema": {
              "example": 2024,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/WithholdingTaxListResponse"
                }
              }
            },
            "description": "Withholding records for payee retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get withholding by payee (支払先別源泉徴収)",
        "tags": [
          "Tax Compliance"
        ]
      }
    },
    "/tax/withholding/calculate": {
      "post": {
        "description": "Calculate withholding tax for a salary payment using 甲欄/乙欄 rates.\n\n## Salary Withholding Calculation (v4.43)\nServer-side gross-to-net calculation with:\n- **甲欄 (Kou)**: Primary workplace - uses dependent count table lookup\n- **乙欄 (Otsu)**: Secondary workplace - printed 乙欄 amount (3.063% below the first bracket)\n\n## Calculation Logic\n1. Calculate taxable income: grossSalary - socialInsurance\n2. Find matching row in tax table\n3. Apply 甲欄 (table lookup by dependents; over 7, less 1,610円 per extra person) or 乙欄. From 740,000円 the NTA formula bands apply.\n4. Calculate net salary: grossSalary - socialInsurance - withholdingTax\n\n## 甲欄 vs 乙欄\n- **甲欄**: 扶養控除等申告書を提出した従業員（主たる給与）\n- **乙欄**: 申告書未提出または従たる給与（税率が高い）",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "kou_example": {
                  "summary": "甲欄・扶養2人",
                  "value": {
                    "dependents": 2,
                    "gross_salary": 350000,
                    "social_insurance": 50000,
                    "tax_column": "kou",
                    "year": 2025
                  }
                },
                "otsu_example": {
                  "summary": "乙欄（従たる給与）",
                  "value": {
                    "gross_salary": 200000,
                    "social_insurance": 30000,
                    "tax_column": "otsu",
                    "year": 2025
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/SalaryCalculationRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/SalaryCalculationResult"
                    },
                    "message": {
                      "example": "源泉徴収税額を計算しました",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Withholding tax calculated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Calculate salary withholding (給与源泉税計算)",
        "tags": [
          "Tax Compliance"
        ]
      }
    },
    "/tax/withholding/calculate-batch": {
      "post": {
        "description": "Calculate withholding tax for multiple employees in one request.\n\n## Batch Calculation (v4.43)\nEfficient payroll processing with:\n- **Multiple Employees**: Process all employees in one API call\n- **Individual Results**: Get results for each employee\n- **Summary Totals**: Aggregated totals for payroll\n\n## Error Handling\n- Individual calculation errors don't fail the entire batch\n- Each result includes an optional error field\n- Summary includes success/error counts",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/BatchCalculationRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/BatchCalculationResult"
                    },
                    "message": {
                      "example": "2件の源泉徴収税額を計算しました",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Batch calculation completed"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Batch calculate withholding (一括源泉税計算)",
        "tags": [
          "Tax Compliance"
        ]
      }
    },
    "/tax/withholding/calculate-contractor": {
      "post": {
        "description": "Calculate withholding tax for contractor/interest payments.\n\n## Separate from Salary Withholding\nThis endpoint handles **contractor/freelancer** withholding, which uses flat rates.\nFor salary withholding (給与源泉), use the existing `POST /tax/withholding/calculate`.\n\n## Calculation Logic\n- **Under ¥1,000,000**: rate × gross_amount\n- **Over ¥1,000,000**: rate × 1,000,000 + higher_rate × (gross_amount - 1,000,000)\n- **Non-resident**: Fixed 20.42% rate\n\n## Supported Types\n- `professional_fees`: 報酬・料金等 (10.21%)\n- `royalties`: 使用料等 (10.21%)\n- `rent`: 不動産賃料 (10.21%)\n- `interest`: 利子 (15.315%)\n- `dividends`: 配当等 (20.42%)\n- `prizes`: 賞金 (10.21%)",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "contractor_type": {
                    "description": "Type of contractor payment",
                    "enum": [
                      "professional_fees",
                      "royalties",
                      "rent",
                      "interest",
                      "dividends",
                      "prizes"
                    ],
                    "example": "professional_fees",
                    "type": "string"
                  },
                  "gross_amount": {
                    "description": "Gross payment amount in JPY",
                    "example": 500000,
                    "minimum": 0,
                    "type": "number"
                  },
                  "is_resident": {
                    "default": true,
                    "description": "Whether the contractor is a Japanese resident",
                    "type": "boolean"
                  }
                },
                "required": [
                  "gross_amount",
                  "contractor_type"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "calculation_details": {
                          "properties": {
                            "base_rate": {
                              "type": "number"
                            },
                            "higher_rate": {
                              "nullable": true,
                              "type": "number"
                            },
                            "threshold": {
                              "nullable": true,
                              "type": "number"
                            }
                          },
                          "type": "object"
                        },
                        "contractor_type": {
                          "example": "professional_fees",
                          "type": "string"
                        },
                        "gross_amount": {
                          "example": 500000,
                          "type": "number"
                        },
                        "is_resident": {
                          "example": true,
                          "type": "boolean"
                        },
                        "net_amount": {
                          "example": 448950,
                          "type": "number"
                        },
                        "tax_rate": {
                          "example": 0.1021,
                          "type": "number"
                        },
                        "withholding_tax": {
                          "example": 51050,
                          "type": "number"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "外注源泉税を計算しました",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Withholding tax calculated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Calculate contractor withholding tax (外注源泉計算)",
        "tags": [
          "Tax Compliance"
        ]
      }
    },
    "/tax/withholding/compliance-check": {
      "get": {
        "description": "Check the company's withholding tax compliance status.\n\n## Compliance Check (v4.43)\nValidates compliance with:\n- **Tax Table Version**: Using current NTA-published rates\n- **Payment Deadlines**: Upcoming 納付期限 warnings\n- **年末調整 Eligibility**: Based on 甲欄/乙欄 status\n- **確定申告 Requirements**: Reminders for 乙欄 users\n\n## Company Status\n- **isMultipleWorkplaceEmployee**: 二以上事業所勤務者 flag\n- **taxColumn**: kou (甲欄) or otsu (乙欄)\n- **yearEndAdjustmentEligible**: Can perform 年末調整\n- **kakuteishinkokuRequired**: Must file 確定申告",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/ComplianceCheckResult"
                    },
                    "message": {
                      "example": "提出準備チェックを実行しました",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Compliance check completed"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Check tax compliance status (コンプライアンスチェック)",
        "tags": [
          "Tax Compliance"
        ]
      }
    },
    "/tax/withholding/mark-paid": {
      "post": {
        "description": "Mark multiple withholding tax records as paid in a bulk operation.\n\n## Bulk Payment Processing (一括納付処理)\nProcess tax authority payments with:\n- **Bulk Operations**: Mark multiple records as paid in one operation\n- **Payment Tracking**: Record payment date and reference\n- **Audit Trail**: Complete audit trail for payment processing\n- **Validation**: Validate all records exist and are payable\n- **Amount Calculation**: Calculate total payment amount\n\n## Payment Rules\n- **Pending Records Only**: Only pending records can be marked as paid\n- **User Ownership**: All records must belong to the requesting user\n- **Date Format**: Payment date must be in YYYYMMDD format\n- **Atomic Operation**: All records updated or none (transaction)\n\n## Use Cases\n- **Monthly Payment Processing**: Process monthly withholding tax payments\n- **Tax Authority Submission**: Record payments made to tax authorities\n- **Compliance Tracking**: Track payment compliance and deadlines\n- **Audit Documentation**: Document payment dates for audit purposes\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/MarkAsPaidRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MarkAsPaidResponse"
                }
              }
            },
            "description": "Withholding taxes marked as paid successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "RECORDS_ALREADY_PAID",
                      "type": "string"
                    },
                    "message": {
                      "example": "3件のレコードは既に納付済みです",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Validation error or records already paid"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "RECORDS_NOT_FOUND",
                      "type": "string"
                    },
                    "message": {
                      "example": "次のレコードが見つかりません: xxx-xxx-xxx",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "One or more records not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Mark withholding taxes as paid (源泉徴収税納付済みマーク)",
        "tags": [
          "Tax Compliance"
        ]
      }
    },
    "/tax/withholding/payee-summaries/{year}": {
      "get": {
        "description": "Get annual withholding tax summaries by payee for tax reporting.\n\n## Payee Summary Features\nAnnual payee summaries with:\n- **Annual Totals**: Total payments and withholding by payee\n- **Category Breakdown**: Breakdown by payment category for each payee\n- **Tax Slip Preparation**: Data preparation for withholding tax slips\n- **Compliance Reporting**: Support for annual tax reporting requirements\n- **Payee Management**: Comprehensive payee information management\n\n## Summary Information\n- **Payee Details**: Complete payee information and classification\n- **Annual Totals**: Total gross payments and withholding amounts\n- **Category Analysis**: Breakdown by withholding category\n- **Tax Slip Data**: Data formatted for tax slip generation\n- **Compliance Status**: Compliance status for each payee\n\n## Use Cases\n- **Annual Reporting**: Generate annual withholding tax reports\n- **Tax Slip Generation**: Prepare data for withholding tax slips\n- **Payee Analysis**: Analyze payments by payee\n- **Compliance Monitoring**: Monitor compliance by payee\n- **Audit Preparation**: Prepare payee data for audit\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Year for payee summaries",
            "in": "path",
            "name": "year",
            "required": true,
            "schema": {
              "example": 2024,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "items": {
                        "properties": {
                          "categories": {
                            "items": {
                              "properties": {
                                "category": {
                                  "$ref": "#/components/schemas/WithholdingCategory"
                                },
                                "count": {
                                  "type": "integer"
                                },
                                "grossAmount": {
                                  "format": "decimal",
                                  "type": "number"
                                },
                                "withholdingAmount": {
                                  "format": "decimal",
                                  "type": "number"
                                }
                              },
                              "type": "object"
                            },
                            "type": "array"
                          },
                          "payeeName": {
                            "example": "田中太郎",
                            "type": "string"
                          },
                          "payeeType": {
                            "$ref": "#/components/schemas/PayeeType"
                          },
                          "paymentCount": {
                            "example": 12,
                            "type": "integer"
                          },
                          "totalGrossAmount": {
                            "example": 6000000,
                            "format": "decimal",
                            "type": "number"
                          },
                          "totalWithholdingAmount": {
                            "example": 612600,
                            "format": "decimal",
                            "type": "number"
                          }
                        },
                        "type": "object"
                      },
                      "type": "array"
                    },
                    "message": {
                      "example": "Payee summaries retrieved successfully",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Payee summaries retrieved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get payee summaries by year (支払先別年間集計)",
        "tags": [
          "Tax Compliance"
        ]
      }
    },
    "/tax/withholding/payment-schedule": {
      "get": {
        "description": "Get withholding tax payment schedule for compliance planning.\n\n## Payment Schedule Management\nComprehensive payment scheduling with:\n- **Due Date Tracking**: Track all withholding tax payment due dates\n- **Amount Planning**: Plan payment amounts by due date\n- **Status Monitoring**: Monitor payment status and compliance\n- **Calendar Integration**: Integration with business calendar\n- **Reminder System**: Automated reminder system for due dates\n\n## Schedule Information\n- **Payment Due Dates**: All upcoming withholding tax payment due dates\n- **Payment Amounts**: Amounts due for each payment date\n- **Payment Status**: Current status of each payment\n- **Compliance Tracking**: Track compliance with payment deadlines\n- **Historical Data**: Historical payment data for analysis\n\n## Use Cases\n- **Payment Planning**: Plan withholding tax payments to authorities\n- **Cash Flow Management**: Manage cash flow for tax payments\n- **Compliance Monitoring**: Monitor compliance with payment deadlines\n- **Reminder Management**: Set up reminders for payment due dates\n- **Audit Preparation**: Prepare payment schedule for audit\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Filter by year",
            "in": "query",
            "name": "year",
            "required": false,
            "schema": {
              "example": 2024,
              "type": "integer"
            }
          },
          {
            "description": "Filter by payment status",
            "in": "query",
            "name": "status",
            "required": false,
            "schema": {
              "$ref": "#/components/schemas/WithholdingPaymentStatus"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "items": {
                        "properties": {
                          "amount": {
                            "example": 255250,
                            "format": "decimal",
                            "type": "number"
                          },
                          "dueDate": {
                            "example": "2024-04-10",
                            "type": "string"
                          },
                          "paymentCount": {
                            "example": 15,
                            "type": "integer"
                          },
                          "status": {
                            "$ref": "#/components/schemas/WithholdingPaymentStatus"
                          }
                        },
                        "type": "object"
                      },
                      "type": "array"
                    },
                    "message": {
                      "example": "Payment schedule retrieved successfully",
                      "type": "string"
                    },
                    "statusCode": {
                      "example": 200,
                      "type": "number"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Payment schedule retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get withholding payment schedule (源泉徴収支払スケジュール)",
        "tags": [
          "Tax Compliance"
        ]
      }
    },
    "/tax/withholding/summary": {
      "get": {
        "description": "Get monthly withholding tax summary for compliance reporting.\n\n## Monthly Summary Features\nComprehensive monthly summaries with:\n- **Total Calculations**: Total gross and withholding amounts\n- **Category Breakdown**: Breakdown by payment category\n- **Payment Status**: Track payment status to tax authorities\n- **Due Date Tracking**: Monitor payment due dates\n- **Compliance Monitoring**: Monitor compliance with payment deadlines\n\n## Summary Information\n- **Monthly Totals**: Total gross and withholding amounts for the month\n- **Category Analysis**: Breakdown by withholding category\n- **Payment Tracking**: Track payments to tax authorities\n- **Due Date Management**: Monitor upcoming payment deadlines\n- **Compliance Status**: Overall compliance status for the month\n\n## Use Cases\n- **Monthly Reporting**: Generate monthly withholding tax reports\n- **Payment Planning**: Plan payments to tax authorities\n- **Compliance Monitoring**: Monitor compliance with tax deadlines\n- **Category Analysis**: Analyze withholding by payment category\n- **Audit Preparation**: Prepare withholding data for audit\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Year in YYYY format",
            "in": "query",
            "name": "year",
            "required": true,
            "schema": {
              "example": "2024",
              "pattern": "^\\d{4}$",
              "type": "string"
            }
          },
          {
            "description": "Month in MM format (optional)",
            "in": "query",
            "name": "month",
            "required": false,
            "schema": {
              "example": "03",
              "pattern": "^\\d{2}$",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/WithholdingSummaryResponse"
                }
              }
            },
            "description": "Withholding tax summary retrieved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get withholding tax summary (源泉徴収集計)",
        "tags": [
          "Tax Compliance"
        ]
      }
    },
    "/tax/withholding/table-version": {
      "get": {
        "description": "Get current and next tax table version information.\n\n## Tax Table Version Management (v4.43)\nReturns version information for:\n- **Current Year Table**: Currently active tax table (源泉徴収税額表)\n- **Next Year Table**: Upcoming year's table if available\n- **Tax Reform Notes**: Recent tax reform changes affecting calculations\n\n## Use Cases\n- **Version Check**: Verify which tax table version is in use\n- **Update Notification**: Check if newer table is available\n- **Compliance Verification**: Ensure using latest NTA-published rates\n\n## Reference\n- NTA 源泉徴収税額表: https://www.nta.go.jp/publication/pamph/gensen/zeigakuhyo2026/01.htm",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "currentVersion": {
                          "$ref": "#/components/schemas/TaxTableVersion"
                        },
                        "nextVersion": {
                          "$ref": "#/components/schemas/TaxTableVersion",
                          "nullable": true
                        },
                        "taxReformNotes": {
                          "items": {
                            "properties": {
                              "effectiveDate": {
                                "type": "string"
                              },
                              "name": {
                                "type": "string"
                              },
                              "summary": {
                                "type": "string"
                              },
                              "year": {
                                "type": "integer"
                              }
                            },
                            "type": "object"
                          },
                          "type": "array"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "example": "税額表バージョン情報を取得しました",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Tax table version information retrieved"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get tax table version info (税額表バージョン情報)",
        "tags": [
          "Tax Compliance"
        ]
      }
    },
    "/tax/withholding/tax-table": {
      "get": {
        "description": "Get the actual tax table data for withholding calculations.\n\n## Tax Table Data (v4.43)\nReturns the complete 源泉徴収税額表 data including:\n- **甲欄 (Kou)**: Primary workplace rates by dependent count (0-7人)\n- **乙欄 (Otsu)**: Secondary workplace rates (percentage or fixed)\n- **Salary Ranges**: Min/max salary for each row\n\n## Table Types\n- **monthly**: 月額表 (Monthly salary table)\n- **daily**: 日額表 (Daily salary table)\n- **bonus**: 賞与 (Bonus payment table)\n\n## Use Cases\n- **Frontend Calculation**: Perform client-side tax calculations\n- **Validation**: Verify server-side calculations\n- **Display**: Show tax table to users",
        "parameters": [
          {
            "description": "Tax year (defaults to current year)",
            "in": "query",
            "name": "year",
            "required": false,
            "schema": {
              "example": "2025",
              "pattern": "^\\d{4}$",
              "type": "string"
            }
          },
          {
            "description": "Table type",
            "in": "query",
            "name": "type",
            "required": false,
            "schema": {
              "default": "monthly",
              "enum": [
                "monthly",
                "daily",
                "bonus"
              ],
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/TaxTableData"
                    },
                    "message": {
                      "example": "令和7年分月額表を取得しました",
                      "type": "string"
                    },
                    "success": {
                      "example": true,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Tax table data retrieved"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "message": {
                      "example": "税額表が見つかりません: 2027年 monthly",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Tax table not found for specified year"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get tax table data (税額表データ取得)",
        "tags": [
          "Tax Compliance"
        ]
      }
    },
    "/tax/withholding/{id}": {
      "delete": {
        "description": "Delete (or cancel) a withholding tax record.\n\n## Deletion Modes\nTwo deletion modes are available for different use cases:\n\n### Soft Delete (Default)\n- Sets status to 'cancelled'\n- Preserves audit trail for tax compliance\n- Record remains in database but excluded from reports\n- **Recommended for production use**\n\n### Hard Delete\n- Permanently removes the record\n- Use only for development/testing or data correction\n- Cannot be undone\n\n## Deletion Rules\n- **Paid Records**: Cannot delete records that have been paid (audit compliance)\n- **Pending/Scheduled**: Can be deleted (soft or hard)\n- **Cancelled Records**: Already soft-deleted, can be hard-deleted\n\n## Audit Compliance\nFor Japanese tax compliance, soft delete is recommended as it:\n- Maintains complete audit trail\n- Allows reconstruction of historical data\n- Satisfies regulatory record-keeping requirements\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Withholding tax record ID to delete",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "If true, permanently delete the record. If false (default), soft delete by setting status to cancelled.",
            "in": "query",
            "name": "hard_delete",
            "required": false,
            "schema": {
              "default": false,
              "type": "boolean"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DeleteWithholdingResponse"
                }
              }
            },
            "description": "Withholding tax record deleted successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "CANNOT_DELETE_PAID_RECORD",
                      "type": "string"
                    },
                    "message": {
                      "example": "納付済みの源泉徴収レコードは削除できません",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Cannot delete paid record"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Delete withholding tax record (源泉徴収レコード削除)",
        "tags": [
          "Tax Compliance"
        ]
      },
      "get": {
        "description": "Get a single withholding tax record by ID.\n\n## Record Details\nRetrieve complete record information with:\n- **Payment Information**: Gross amount, withholding amount, net amount\n- **Payee Details**: Name, type, address, My Number\n- **Tax Information**: Rate, category, due date, payment status\n- **Audit Information**: Created and updated timestamps\n- **Related Records**: Linked expense and journal entry IDs\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Withholding tax record ID",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/WithholdingTaxResponse"
                }
              }
            },
            "description": "Withholding tax record retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get withholding tax record (源泉徴収レコード取得)",
        "tags": [
          "Tax Compliance"
        ]
      },
      "patch": {
        "description": "Update an existing withholding tax record.\n\n## Update Rules\n- **Partial Updates**: Only provided fields will be updated\n- **Recalculation**: Changing gross_amount or rate triggers automatic recalculation\n- **Paid Records**: Cannot modify records that are already paid\n- **Audit Trail**: All changes are tracked with timestamps\n\n## Recalculation Logic\nWhen gross_amount or withholding_rate changes:\n- **10.21% Rate**: Applied to payments under ¥1,000,000\n- **20.42% Rate**: Applied to payments over ¥1,000,000\n- **Custom Rate**: If withholding_rate is provided, it overrides automatic calculation\n- **Net Amount**: Automatically calculated as gross_amount - withholding_amount\n\n## Validation\n- **Date Format**: payment_date must be in YYYYMMDD format\n- **Rate Range**: withholding_rate must be between 0 and 1\n- **Positive Amount**: gross_amount must be positive\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Withholding tax record ID to update",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/UpdateWithholdingTaxRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/WithholdingTaxResponse"
                }
              }
            },
            "description": "Withholding tax record updated successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "RECORD_ALREADY_PAID",
                      "type": "string"
                    },
                    "message": {
                      "example": "納付済みの源泉徴収レコードは変更できません",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Validation error or record is paid"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update withholding tax record (源泉徴収レコード更新)",
        "tags": [
          "Tax Compliance"
        ]
      }
    },
    "/tax/withholding/{id}/generate-slip": {
      "post": {
        "description": "Generate withholding tax slip (源泉徴収票) for annual tax reporting.\n\n## Withholding Slip Generation (源泉徴収票生成)\nOfficial tax slip generation with:\n- **Annual Compilation**: Compile all payments for the tax year\n- **Category Breakdown**: Breakdown by withholding category\n- **Official Format**: Generate in official Japanese tax format\n- **Payee Information**: Complete payee information and classification\n- **Compliance Validation**: Validate compliance with tax requirements\n\n## Slip Contents\n- **Payee Information**: Name, address, and classification\n- **Annual Totals**: Total gross payments and withholding amounts\n- **Category Details**: Breakdown by payment category with codes\n- **Tax Year**: Specific tax year for the slip\n- **Official Format**: Formatted according to Japanese tax standards\n\n## Use Cases\n- **Annual Reporting**: Generate annual withholding tax slips\n- **Tax Compliance**: Meet Japanese tax reporting requirements\n- **Payee Documentation**: Provide documentation to payees\n- **Audit Support**: Support tax audit requirements\n- **Regulatory Compliance**: Comply with tax authority requirements\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Withholding tax record ID",
            "in": "path",
            "name": "id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Tax year for slip generation (defaults to current year)",
            "in": "query",
            "name": "year",
            "required": false,
            "schema": {
              "example": 2024,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/WithholdingSlipResponse"
                }
              }
            },
            "description": "Withholding slip generated successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Generate withholding slip (源泉徴収票生成)",
        "tags": [
          "Tax Compliance"
        ]
      }
    },
    "/test-scripts/execute": {
      "post": {
        "description": "Persist a test script execution result.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ExecuteTestScriptRequest"
              }
            }
          }
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/TestScriptExecutionResponse"
                }
              }
            },
            "description": "Execution result saved"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Save test script execution result",
        "tags": [
          "Test Scripts"
        ]
      }
    },
    "/test-scripts/executions": {
      "get": {
        "description": "Get paginated history of test script executions.",
        "parameters": [
          {
            "in": "query",
            "name": "page_size",
            "schema": {
              "default": 20,
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "page_number",
            "schema": {
              "default": 1,
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "company_id",
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "script_id",
            "schema": {
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "script_category",
            "schema": {
              "$ref": "#/components/schemas/TestScriptCategory"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Executions list retrieved"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "List test script executions",
        "tags": [
          "Test Scripts"
        ]
      }
    },
    "/test-scripts/executions/by-script": {
      "get": {
        "description": "Get the latest execution for each unique script_id.",
        "parameters": [
          {
            "in": "query",
            "name": "company_id",
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Latest executions by script retrieved"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get latest execution per script",
        "tags": [
          "Test Scripts"
        ]
      }
    },
    "/test-scripts/executions/latest": {
      "get": {
        "description": "Get the most recent execution, optionally filtered by script_id.",
        "parameters": [
          {
            "in": "query",
            "name": "script_id",
            "schema": {
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "company_id",
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Latest execution retrieved"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get latest execution",
        "tags": [
          "Test Scripts"
        ]
      }
    },
    "/test-scripts/executions/{executionId}": {
      "get": {
        "parameters": [
          {
            "in": "path",
            "name": "executionId",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Execution retrieved"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get execution by ID",
        "tags": [
          "Test Scripts"
        ]
      }
    },
    "/trial-balance": {
      "get": {
        "description": "Generate comprehensive Japanese trial balance (試算表) for specified date range with detailed account analysis.\n\n## Japanese Trial Balance Generation (試算表作成)\nComprehensive trial balance reporting with:\n- **Opening Balances (期首残高)**: Account balances at the beginning of the period\n- **Period Activity (当期発生額)**: Debit and credit activity during the period\n- **Closing Balances (期末残高)**: Account balances at the end of the period\n- **Balance Validation**: Ensures total debits equal total credits\n- **Account Categorization**: Organized by account type (asset, liability, equity, revenue, expense)\n\n## Financial Analysis Features\n- **Account-by-Account Detail**: Individual account analysis with opening, activity, and closing balances\n- **Normal Side Handling**: Proper presentation based on account normal side (debit/credit)\n- **Balance Verification**: Automatic validation of accounting equation integrity\n- **Precision Calculations**: Decimal precision for accurate financial reporting\n- **Audit Trail**: Complete documentation for audit and compliance purposes\n\n## Japanese Accounting Standards\n- **Chart of Accounts**: Integration with Japanese standard chart of accounts\n- **Account Classification**: Proper categorization per Japanese accounting standards\n- **Balance Presentation**: Standard Japanese trial balance format and layout\n- **Fiscal Period**: Support for Japanese fiscal year periods (April-March)\n- **Compliance**: Meets Japanese GAAP requirements for trial balance reporting\n\n## Report Structure\n- **Account Ordering**: Accounts sorted by account code for consistent presentation\n- **Balance Columns**: Opening, period activity, and closing balance columns\n- **Totals Validation**: Grand totals with balance verification\n- **Zero Balance Handling**: Includes accounts with zero balances for completeness\n- **Audit Information**: Generation timestamp and user identification\n\n## Use Cases\n- **Financial Statement Preparation**: Foundation for balance sheet and income statement\n- **Month-End Closing**: Monthly trial balance for closing procedures\n- **Audit Preparation**: Trial balance for external audit working papers\n- **Management Reporting**: Internal financial analysis and review\n- **Compliance Reporting**: Regulatory reporting and tax preparation\n- **Budget Analysis**: Compare actual balances with budgeted amounts\n- **Account Reconciliation**: Verify account balances and identify discrepancies\n\n## Balance Calculation Logic\n- **Opening Balance**: Cumulative balance from all transactions before period start\n- **Period Activity**: Sum of debit and credit transactions during the period\n- **Closing Balance**: Opening balance plus/minus period activity\n- **Normal Side Respect**: Debit balances for assets/expenses, credit balances for liabilities/equity/revenue\n- **Balance Validation**: Ensures accounting equation (Assets = Liabilities + Equity) integrity\n\n## Data Accuracy\n- **Decimal Precision**: High-precision decimal arithmetic for financial accuracy\n- **Transaction Integrity**: Based on posted general ledger transactions\n- **User Scoped**: Results limited to user's accessible accounts and transactions\n- **Date Range Validation**: Ensures valid date range for period analysis\n- **Account Validation**: Includes only active accounts in the trial balance\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Period start date in YYYYMMDD format",
            "example": 20240401,
            "in": "query",
            "name": "start_date",
            "required": true,
            "schema": {
              "maximum": 99991231,
              "minimum": 19000101,
              "type": "integer"
            }
          },
          {
            "description": "Period end date in YYYYMMDD format",
            "example": 20241231,
            "in": "query",
            "name": "end_date",
            "required": true,
            "schema": {
              "maximum": 99991231,
              "minimum": 19000101,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "balanced_trial_balance": {
                    "summary": "Balanced trial balance with validation",
                    "value": {
                      "data": {
                        "generatedAt": "2024-01-15T10:30:00.000Z",
                        "isBalanced": false,
                        "lines": [
                          {
                            "accountCode": "1001",
                            "accountName": "現金",
                            "category": "asset",
                            "closingCredit": 0,
                            "closingDebit": 130000,
                            "openingCredit": 0,
                            "openingDebit": 100000,
                            "periodCredit": 20000,
                            "periodDebit": 50000,
                            "priorPeriodCredit": null,
                            "priorPeriodDebit": null,
                            "variance": null,
                            "variancePercent": null
                          },
                          {
                            "accountCode": "4001",
                            "accountName": "売上高",
                            "category": "revenue",
                            "closingCredit": 50000,
                            "closingDebit": 0,
                            "openingCredit": 0,
                            "openingDebit": 0,
                            "periodCredit": 50000,
                            "periodDebit": 0,
                            "priorPeriodCredit": null,
                            "priorPeriodDebit": null,
                            "variance": null,
                            "variancePercent": null
                          }
                        ],
                        "periodEnd": "2024-01-31",
                        "periodStart": "2024-01-01",
                        "priorPeriodEnd": null,
                        "priorPeriodStart": null,
                        "totals": {
                          "closingCredit": 50000,
                          "closingDebit": 130000,
                          "openingCredit": 0,
                          "openingDebit": 100000,
                          "periodCredit": 70000,
                          "periodDebit": 50000,
                          "priorPeriodCredit": null,
                          "priorPeriodDebit": null
                        }
                      },
                      "message": "Trial balance generated successfully",
                      "statusCode": 200
                    }
                  },
                  "complete_trial_balance": {
                    "summary": "Complete trial balance report",
                    "value": {
                      "data": {
                        "generatedAt": "2024-01-15T10:30:00.000Z",
                        "isBalanced": true,
                        "lines": [
                          {
                            "accountCode": "1001",
                            "accountName": "現金",
                            "category": "asset",
                            "closingCredit": 0,
                            "closingDebit": 700000,
                            "openingCredit": 0,
                            "openingDebit": 500000,
                            "periodCredit": 100000,
                            "periodDebit": 300000,
                            "priorPeriodCredit": null,
                            "priorPeriodDebit": null,
                            "variance": null,
                            "variancePercent": null
                          },
                          {
                            "accountCode": "2001",
                            "accountName": "買掛金",
                            "category": "liability",
                            "closingCredit": 300000,
                            "closingDebit": 0,
                            "openingCredit": 200000,
                            "openingDebit": 0,
                            "periodCredit": 150000,
                            "periodDebit": 50000,
                            "priorPeriodCredit": null,
                            "priorPeriodDebit": null,
                            "variance": null,
                            "variancePercent": null
                          },
                          {
                            "accountCode": "3001",
                            "accountName": "資本金",
                            "category": "equity",
                            "closingCredit": 1000000,
                            "closingDebit": 0,
                            "openingCredit": 1000000,
                            "openingDebit": 0,
                            "periodCredit": 0,
                            "periodDebit": 0,
                            "priorPeriodCredit": null,
                            "priorPeriodDebit": null,
                            "variance": null,
                            "variancePercent": null
                          },
                          {
                            "accountCode": "4001",
                            "accountName": "売上高",
                            "category": "revenue",
                            "closingCredit": 800000,
                            "closingDebit": 0,
                            "openingCredit": 0,
                            "openingDebit": 0,
                            "periodCredit": 800000,
                            "periodDebit": 0,
                            "priorPeriodCredit": null,
                            "priorPeriodDebit": null,
                            "variance": null,
                            "variancePercent": null
                          },
                          {
                            "accountCode": "5001",
                            "accountName": "仕入高",
                            "category": "expense",
                            "closingCredit": 0,
                            "closingDebit": 400000,
                            "openingCredit": 0,
                            "openingDebit": 0,
                            "periodCredit": 0,
                            "periodDebit": 400000,
                            "priorPeriodCredit": null,
                            "priorPeriodDebit": null,
                            "variance": null,
                            "variancePercent": null
                          }
                        ],
                        "periodEnd": "2024-12-31",
                        "periodStart": "2024-04-01",
                        "priorPeriodEnd": null,
                        "priorPeriodStart": null,
                        "totals": {
                          "closingCredit": 2100000,
                          "closingDebit": 1100000,
                          "openingCredit": 1200000,
                          "openingDebit": 500000,
                          "periodCredit": 1050000,
                          "periodDebit": 750000,
                          "priorPeriodCredit": null,
                          "priorPeriodDebit": null
                        }
                      },
                      "message": "Trial balance generated successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/TrialBalanceResponse"
                }
              }
            },
            "description": "Trial balance generated successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "error": {
                      "example": "Invalid date format (use YYYYMMDD) or end date must be after start date",
                      "type": "string"
                    },
                    "fieldErrors": {
                      "additionalProperties": {
                        "items": {
                          "type": "string"
                        },
                        "type": "array"
                      },
                      "example": {
                        "end_date": [
                          "End date must be after start date"
                        ],
                        "start_date": [
                          "Start date must be a number in YYYYMMDD format"
                        ]
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid date parameters or date range"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "422": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "details": {
                      "properties": {
                        "affectedAccounts": {
                          "example": [
                            "1001",
                            "4001"
                          ],
                          "items": {
                            "type": "string"
                          },
                          "type": "array"
                        },
                        "imbalance": {
                          "example": 100000,
                          "type": "number"
                        },
                        "totalCredits": {
                          "example": 1400000,
                          "type": "number"
                        },
                        "totalDebits": {
                          "example": 1500000,
                          "type": "number"
                        }
                      },
                      "type": "object"
                    },
                    "error": {
                      "example": "Trial balance calculation failed due to data inconsistency",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Trial balance calculation error or data inconsistency"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Generate trial balance for date range",
        "tags": [
          "Trial Balance"
        ]
      }
    },
    "/user-activity": {
      "post": {
        "description": "Record a new user activity with full metadata support.\n\n**Rate Limit:** 600 requests per 15 minutes\n\n**🔄 Case Convention:** Send all fields in `camelCase`. The middleware automatically handles conversion.\n\n**Best Practices:**\n- Include `sessionId` for grouping\n- Set `isError: true` for error events\n- Use `timestamp` for offline sync",
        "requestBody": {
          "content": {
            "application/json": {
              "example": {
                "actionLabel": "給与明細書を編集中",
                "actionType": "document_edit",
                "browser": "Chrome 120",
                "deviceType": "desktop",
                "entityId": "abc-123-def-456",
                "entityName": "2025年1月 給与明細書",
                "entityType": "document",
                "os": "Windows 11",
                "route": "/documents/abc-123",
                "routeParams": {
                  "documentId": "abc-123"
                },
                "sessionId": "sess_abc123"
              },
              "schema": {
                "$ref": "#/components/schemas/RecordActivityRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/UserActivity"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Activity recorded successfully"
          },
          "429": {
            "description": "Rate limit exceeded"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Record single activity",
        "tags": [
          "User Activity"
        ]
      }
    },
    "/user-activity/batch": {
      "post": {
        "description": "Record multiple activities in a single request.\n\n**Rate Limit:** 60 requests per 15 minutes (max 100 activities per batch)\n\n**🔄 Case Convention:** Send all fields in `camelCase`. The middleware automatically handles conversion.\n\n**Best Practices:**\n- Queue activities and flush every 5-10 seconds\n- Include common metadata (`sessionId`, `deviceType`) at root level\n- Use `sequenceNumber` to preserve order",
        "requestBody": {
          "content": {
            "application/json": {
              "example": {
                "activities": [
                  {
                    "actionLabel": "ダッシュボード訪問",
                    "actionType": "page_visit",
                    "route": "/dashboard",
                    "sequenceNumber": 0
                  },
                  {
                    "actionLabel": "書類を閲覧",
                    "actionType": "document_view",
                    "entityId": "uuid",
                    "entityType": "document",
                    "route": "/documents/123",
                    "sequenceNumber": 1
                  }
                ],
                "browser": "Chrome 120",
                "deviceType": "desktop",
                "os": "Windows 11",
                "sessionId": "sess_abc123"
              },
              "schema": {
                "$ref": "#/components/schemas/BatchRecordRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/BatchRecordResponse"
                    },
                    "message": {
                      "type": "string"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Batch recorded"
          },
          "429": {
            "description": "Rate limit exceeded"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Record batch activities",
        "tags": [
          "User Activity"
        ]
      }
    },
    "/user-activity/entity/{entity_type}/{entity_id}": {
      "get": {
        "description": "Get activities for a specific entity (e.g., all activities for a document).",
        "parameters": [
          {
            "in": "path",
            "name": "entity_type",
            "required": true,
            "schema": {
              "type": "string"
            }
          },
          {
            "in": "path",
            "name": "entity_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "limit",
            "schema": {
              "default": 10,
              "maximum": 100,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "items": {
                        "$ref": "#/components/schemas/UserActivity"
                      },
                      "type": "array"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Entity activities"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get activities by entity",
        "tags": [
          "User Activity"
        ]
      }
    },
    "/user-activity/export": {
      "get": {
        "description": "Export user activity logs to CSV or JSON format with proper Content-Disposition headers for browser download.\n\n## Enterprise Features\n- **SOC2 compliant audit trail format**\n- **Date range filtering** (Unix timestamps)\n- **Action type filtering**\n- **Error-only filtering**\n- **UTF-8 BOM** for Excel compatibility\n\n## CSV Format (SOC2 Audit Trail)\nHeaders:\n```\ntimestamp,user_id,session_id,action_type,action_label,route,entity_type,entity_id,entity_name,is_error,error_message,duration_ms,device_type,browser,os\n```\n\n## Response Headers\n- **Content-Type**: `text/csv; charset=utf-8` or `application/json; charset=utf-8`\n- **Content-Disposition**: `attachment; filename=\"activity-logs-2026-01-12.csv\"`\n\n## Frontend Integration\n```javascript\n// Convert date to Unix timestamp (seconds)\nconst fromTimestamp = Math.floor(new Date('2026-01-01').getTime() / 1000);\nconst toTimestamp = Math.floor(new Date('2026-01-31').getTime() / 1000);\n\n// Direct browser navigation triggers download\nconst params = new URLSearchParams({\n  format: 'csv',\n  from_date: String(fromTimestamp),\n  to_date: String(toTimestamp),\n  errors_only: 'false',\n  limit: '10000'\n});\n\nwindow.location.href = `${API_BASE}/api/user-activity/export?${params}`;\n```",
        "parameters": [
          {
            "description": "Export format (csv or json)",
            "in": "query",
            "name": "format",
            "schema": {
              "default": "csv",
              "enum": [
                "csv",
                "json"
              ],
              "type": "string"
            }
          },
          {
            "description": "Start date filter (Unix timestamp in seconds)",
            "in": "query",
            "name": "from_date",
            "schema": {
              "example": 1704067200,
              "type": "integer"
            }
          },
          {
            "description": "End date filter (Unix timestamp in seconds)",
            "in": "query",
            "name": "to_date",
            "schema": {
              "example": 1736083200,
              "type": "integer"
            }
          },
          {
            "description": "Filter by session ID",
            "in": "query",
            "name": "session_id",
            "schema": {
              "maxLength": 64,
              "type": "string"
            }
          },
          {
            "description": "Filter by action types (comma-separated)",
            "in": "query",
            "name": "action_types",
            "schema": {
              "example": "document_create,document_edit,ai_analyze",
              "type": "string"
            }
          },
          {
            "description": "Only export error entries",
            "in": "query",
            "name": "errors_only",
            "schema": {
              "default": false,
              "type": "boolean"
            }
          },
          {
            "description": "Maximum number of records to export",
            "in": "query",
            "name": "limit",
            "schema": {
              "default": 10000,
              "maximum": 50000,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "items": {
                    "properties": {
                      "action_label": {
                        "type": "string"
                      },
                      "action_type": {
                        "type": "string"
                      },
                      "browser": {
                        "type": "string"
                      },
                      "device_type": {
                        "type": "string"
                      },
                      "duration_ms": {
                        "type": "number"
                      },
                      "entity_id": {
                        "type": "string"
                      },
                      "entity_name": {
                        "type": "string"
                      },
                      "entity_type": {
                        "type": "string"
                      },
                      "error_message": {
                        "type": "string"
                      },
                      "is_error": {
                        "type": "boolean"
                      },
                      "metadata": {
                        "type": "object"
                      },
                      "os": {
                        "type": "string"
                      },
                      "route": {
                        "type": "string"
                      },
                      "session_id": {
                        "type": "string"
                      },
                      "timestamp": {
                        "format": "date-time",
                        "type": "string"
                      },
                      "user_id": {
                        "type": "string"
                      }
                    },
                    "type": "object"
                  },
                  "type": "array"
                }
              },
              "text/csv": {
                "example": "timestamp,user_id,session_id,action_type,action_label,route,entity_type,entity_id,entity_name,is_error,error_message,duration_ms,device_type,browser,os\\r\\n2026-01-12T10:30:00.000Z,user-123,sess-456,document_create,書類を作成,/documents/new,document,doc-789,見積書_ABC株式会社,false,,150,desktop,Chrome,Windows",
                "schema": {
                  "format": "binary",
                  "type": "string"
                }
              }
            },
            "description": "File download with Content-Disposition header",
            "headers": {
              "Content-Disposition": {
                "description": "Attachment filename",
                "schema": {
                  "example": "attachment; filename=\"activity-logs-2026-01-12.csv\"",
                  "type": "string"
                }
              }
            }
          },
          "401": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "User not authenticated"
          },
          "500": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            },
            "description": "Internal server error"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Export activity logs (処理ログエクスポート)",
        "tags": [
          "User Activity"
        ]
      }
    },
    "/user-activity/history": {
      "get": {
        "description": "Get paginated activity history with optional filters.",
        "parameters": [
          {
            "in": "query",
            "name": "limit",
            "schema": {
              "default": 10,
              "maximum": 100,
              "minimum": 1,
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "offset",
            "schema": {
              "default": 0,
              "minimum": 0,
              "type": "integer"
            }
          },
          {
            "in": "query",
            "name": "from_date",
            "schema": {
              "format": "date-time",
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "to_date",
            "schema": {
              "format": "date-time",
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "session_id",
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/PaginatedActivityResponse"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Activity history"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get activity history",
        "tags": [
          "User Activity"
        ]
      }
    },
    "/user-activity/latest": {
      "get": {
        "description": "Get the most recent activity for \"resume where you left off\" feature.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "oneOf": [
                        {
                          "$ref": "#/components/schemas/UserActivity"
                        },
                        {
                          "type": "null"
                        }
                      ]
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Latest activity"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get latest activity",
        "tags": [
          "User Activity"
        ]
      }
    },
    "/user-activity/retention-policy": {
      "get": {
        "description": "Get the current retention policy configuration.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/RetentionPolicy"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Retention policy"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get retention policy",
        "tags": [
          "User Activity"
        ]
      }
    },
    "/user-activity/search": {
      "post": {
        "description": "Search activities with advanced filters.\n\n**Rate Limit:** 100 requests per 15 minutes",
        "requestBody": {
          "content": {
            "application/json": {
              "example": {
                "actionTypes": [
                  "document_view",
                  "document_edit"
                ],
                "errorsOnly": false,
                "fromDate": "2026-01-01T00:00:00Z",
                "limit": 20,
                "toDate": "2026-01-08T23:59:59Z"
              },
              "schema": {
                "$ref": "#/components/schemas/SearchActivityRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/PaginatedActivityResponse"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Search results"
          },
          "429": {
            "description": "Rate limit exceeded"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Search activities",
        "tags": [
          "User Activity"
        ]
      }
    },
    "/user-activity/session/{session_id}": {
      "get": {
        "description": "Get all activities for a specific session in chronological order.",
        "parameters": [
          {
            "in": "path",
            "name": "session_id",
            "required": true,
            "schema": {
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "limit",
            "schema": {
              "default": 100,
              "maximum": 1000,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "items": {
                        "$ref": "#/components/schemas/UserActivity"
                      },
                      "type": "array"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Session activities"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get activities by session",
        "tags": [
          "User Activity"
        ]
      }
    },
    "/user-activity/sessions": {
      "get": {
        "description": "Get summaries of user sessions with activity counts and metadata.",
        "parameters": [
          {
            "in": "query",
            "name": "limit",
            "schema": {
              "default": 10,
              "maximum": 50,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "items": {
                        "$ref": "#/components/schemas/SessionSummary"
                      },
                      "type": "array"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Session summaries"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get session summaries",
        "tags": [
          "User Activity"
        ]
      }
    },
    "/user-activity/stats": {
      "get": {
        "description": "Get comprehensive activity statistics including session and error counts.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/ActivityStats"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Activity statistics"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get activity statistics",
        "tags": [
          "User Activity"
        ]
      }
    },
    "/user-activity/type/{action_type}": {
      "get": {
        "description": "Get activities filtered by action type.",
        "parameters": [
          {
            "in": "path",
            "name": "action_type",
            "required": true,
            "schema": {
              "enum": [
                "document_view",
                "document_edit",
                "document_create",
                "document_delete",
                "document_generate",
                "document_download",
                "document_print",
                "document_send",
                "document_share",
                "document_sign",
                "document_stamp",
                "document_archive",
                "document_restore",
                "document_duplicate",
                "document_update",
                "document_lock",
                "document_unlock",
                "document_void",
                "settings_company",
                "settings_accounting",
                "settings_auth",
                "settings_inkan",
                "settings_signature",
                "settings_profile",
                "settings_notification",
                "settings_payment",
                "settings_integration",
                "settings_export",
                "settings_import",
                "journal_entry",
                "journal_view",
                "journal_delete",
                "journal_approve",
                "journal_reject",
                "bank_reconcile",
                "fiscal_period",
                "account_create",
                "account_edit",
                "account_delete",
                "account_view",
                "trial_balance_view",
                "trial_balance_export",
                "report_view",
                "report_generate",
                "report_export",
                "report_print",
                "report_schedule",
                "client_create",
                "client_edit",
                "client_delete",
                "client_view",
                "ai_chat",
                "ai_suggestion_accept",
                "ai_suggestion_reject",
                "ai_reconcile",
                "ai_analyze",
                "page_visit",
                "session_start",
                "session_end",
                "session_resume",
                "tab_switch",
                "modal_open",
                "modal_close",
                "search_execute",
                "filter_apply",
                "sort_change",
                "form_submit",
                "form_save_draft",
                "form_validation_error",
                "error_occurred",
                "api_error",
                "network_error",
                "login",
                "logout",
                "password_change",
                "mfa_enable",
                "mfa_disable",
                "bulk_upload",
                "bulk_delete",
                "csv_import",
                "csv_export",
                "other"
              ],
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "limit",
            "schema": {
              "default": 10,
              "maximum": 100,
              "minimum": 1,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "items": {
                        "$ref": "#/components/schemas/UserActivity"
                      },
                      "type": "array"
                    },
                    "success": {
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Activities by type"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get activities by type",
        "tags": [
          "User Activity"
        ]
      }
    },
    "/user-profile/ai-settings": {
      "get": {
        "description": "Retrieve the user's AI settings configuration including provider selection and API keys.\n\n## Response Data\nReturns AI settings with:\n- **Provider Configuration**: Selected AI provider and model\n- **System vs Custom**: Whether using system or custom API keys\n- **API Keys**: Masked for security in responses\n- **Firecrawl Integration**: Optional web scraping API configuration\n\n## AI Provider Options\nSupported providers:\n- **OpenAI (0)**: GPT models with OpenAI API\n- **Claude (1)**: Anthropic's Claude models\n- **Together (2)**: Open-source model hosting\n- **Gemini (3)**: Google's Gemini models\n- **OpenRouter (4)**: Multi-provider API gateway\n- **Firecrawl (5)**: Web scraping and content extraction\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "custom_settings": {
                    "summary": "User with custom AI settings",
                    "value": {
                      "data": {
                        "api_key": "****************",
                        "firecrawl_api_key": "****************",
                        "provider": 0,
                        "selected_model": "gpt-4",
                        "use_system": false
                      },
                      "message": "AI settings retrieved successfully",
                      "statusCode": 200
                    }
                  },
                  "system_settings": {
                    "summary": "User using system AI settings",
                    "value": {
                      "data": {
                        "provider": 1,
                        "selected_model": "claude-3-opus-20240229",
                        "use_system": true
                      },
                      "message": "AI settings retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/AISettingsResponse"
                }
              }
            },
            "description": "AI settings retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "PROFILE_NOT_FOUND",
                      "type": "string"
                    },
                    "error": {
                      "example": "User profile not found",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "User profile not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get AI settings",
        "tags": [
          "User Profile"
        ]
      },
      "put": {
        "description": "Update the user's AI settings configuration with validation.\n\n## Request Body\nAI settings configuration:\n- **use_system**: Boolean indicating whether to use system or custom settings\n- **provider**: AI provider selection (0-5, see provider options)\n- **api_key**: Required when use_system is false, optional when true\n- **selected_model**: Model identifier for the selected provider\n- **firecrawl_api_key**: Optional Firecrawl API key\n\n## Validation Rules\n- **Conditional API Key**: api_key is required when use_system is false\n- **Provider Validation**: Must be valid AIProvider enum value (0-5)\n- **Model Validation**: selected_model must be a non-empty string\n\n## Provider-Model Combinations\n- **OpenAI**: gpt-4, gpt-4-turbo, gpt-3.5-turbo\n- **Claude**: claude-3-opus-20240229, claude-3-sonnet-20240229\n- **Together**: meta-llama/Llama-2-70b-chat-hf, mistralai/Mixtral-8x7B-Instruct-v0.1\n- **Gemini**: gemini-pro, gemini-pro-vision\n- **OpenRouter**: Various models through OpenRouter API\n- **Firecrawl**: Web scraping service, not for text generation\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "custom_openai": {
                  "summary": "Custom OpenAI configuration",
                  "value": {
                    "api_key": "sk-proj-abc123...",
                    "firecrawl_api_key": "fc-xyz789...",
                    "provider": 0,
                    "selected_model": "gpt-4",
                    "use_system": false
                  }
                },
                "custom_together": {
                  "summary": "Custom Together AI configuration",
                  "value": {
                    "api_key": "together_api_key_here",
                    "provider": 2,
                    "selected_model": "meta-llama/Llama-2-70b-chat-hf",
                    "use_system": false
                  }
                },
                "system_claude": {
                  "summary": "System Claude configuration",
                  "value": {
                    "provider": 1,
                    "selected_model": "claude-3-opus-20240229",
                    "use_system": true
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/AISettingsSchema"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AISettingsUpdateResponse"
                }
              }
            },
            "description": "AI settings updated successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "VALIDATION_ERROR",
                      "type": "string"
                    },
                    "error": {
                      "example": "API key is required when not using system settings",
                      "type": "string"
                    },
                    "fieldErrors": {
                      "additionalProperties": {
                        "items": {
                          "type": "string"
                        },
                        "type": "array"
                      },
                      "example": {
                        "api_key": [
                          "api_key should not be empty"
                        ]
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid AI settings or validation errors"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "PROFILE_NOT_FOUND",
                      "type": "string"
                    },
                    "error": {
                      "example": "User profile not found",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "User profile not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update AI settings",
        "tags": [
          "User Profile"
        ]
      }
    },
    "/user-profile/document-viewer-config": {
      "get": {
        "description": "Retrieve the specific document viewer configuration settings for the user.\n\n## Response Data\nReturns the document viewer settings including:\n- **Typography**: Font size and family settings\n- **Layout**: Density and width constraints\n- **Visual**: Color schemes, borders, and shadows\n- **Print**: Optimized settings for printing\n\n## Use Cases\n- **Frontend Initialization**: Load viewer settings when opening a document\n- **Theme Application**: Apply visual preferences to the document interface\n- **Print Layout**: Configure print styles before printing\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "standard_config": {
                    "summary": "Standard document viewer configuration",
                    "value": {
                      "data": {
                        "color_scheme": 0,
                        "document_style_variant": 0,
                        "font_family": 0,
                        "font_size": 2,
                        "layout_density": 1,
                        "max_width": 1,
                        "print_color_scheme": 1,
                        "print_font_size": 1,
                        "selected_preset_id": null,
                        "show_borders": true,
                        "show_line_numbers": false,
                        "show_shadows": true
                      },
                      "message": "Document viewer configuration retrieved successfully",
                      "statusCode": 200
                    }
                  },
                  "with_preset": {
                    "summary": "Configuration with Japanese aesthetic preset",
                    "value": {
                      "data": {
                        "color_scheme": 2,
                        "document_style_variant": 1,
                        "font_family": 1,
                        "font_size": 2,
                        "layout_density": 1,
                        "max_width": 1,
                        "print_color_scheme": 1,
                        "print_font_size": 1,
                        "selected_preset_id": "preset-wabi",
                        "show_borders": true,
                        "show_line_numbers": false,
                        "show_shadows": false
                      },
                      "message": "Document viewer configuration retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/DocumentViewerConfigResponse"
                }
              }
            },
            "description": "Document viewer configuration retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "PROFILE_NOT_FOUND",
                      "type": "string"
                    },
                    "error": {
                      "example": "User profile not found",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "User profile not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get document viewer configuration",
        "tags": [
          "User Profile"
        ]
      },
      "put": {
        "description": "Update the document viewer configuration settings for the user.\n      \n## Update Behavior\n- **Full Replacement**: The provided configuration object is validated and applied.\n- **Partial Updates**: Fields not included in the request are not modified (if validation allows optional).\n- **Validation**: Enums are validated against allowed integer values.\n\n## Configuration Options\n- **font_size**: 0 (XS), 1 (SM), 2 (BASE), 3 (LG), 4 (XL)\n- **font_family**: 0 (DEFAULT), 1 (MINCHO), 2 (GOTHIC), 3 (MONO)\n- **layout_density**: 0 (COMPACT), 1 (NORMAL), 2 (SPACIOUS)\n- **max_width**: 0 (NARROW), 1 (NORMAL), 2 (WIDE), 3 (FULL)\n- **color_scheme**: 0 (DEFAULT), 1 (HIGH_CONTRAST), 2 (SEPIA), 3 (DARK)\n- **print_font_size**: 0 (XS) to 4 (XL)\n- **print_color_scheme**: 0 (DEFAULT), 1 (PRINT_FRIENDLY)\n\n## Document Style Variants (v4.28)\n- **document_style_variant**: 0 (STANDARD), 1 (TRADITIONAL), 2 (MINIMAL), 3 (FORMAL), 4 (MODERN)\n\n## Preset Selection (v4.28)\n- **selected_preset_id**: Preset ID string or null\n- Built-in presets: `preset-wabi`, `preset-miyabi`, `preset-zen`, `preset-iki`, `preset-rin`\n- Custom presets: `custom-{timestamp}` format\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "apply_preset": {
                  "summary": "Apply a Japanese aesthetic preset",
                  "value": {
                    "document_style_variant": 1,
                    "selected_preset_id": "preset-wabi"
                  }
                },
                "custom_preset": {
                  "summary": "Apply a custom user preset",
                  "value": {
                    "document_style_variant": 2,
                    "selected_preset_id": "custom-1704067200000"
                  }
                },
                "update_config": {
                  "summary": "Update document viewer settings",
                  "value": {
                    "color_scheme": 3,
                    "document_style_variant": 4,
                    "font_family": 2,
                    "font_size": 3,
                    "layout_density": 2,
                    "max_width": 2,
                    "print_color_scheme": 1,
                    "print_font_size": 2,
                    "selected_preset_id": null,
                    "show_borders": false,
                    "show_line_numbers": true,
                    "show_shadows": false
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/DocumentViewerConfig"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "success_response": {
                    "summary": "Success response",
                    "value": {
                      "data": "Document viewer config updated successfully",
                      "message": "Document viewer config updated successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/UpdateDocumentViewerConfigResponse"
                }
              }
            },
            "description": "Document viewer config updated successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "VALIDATION_ERROR",
                      "type": "string"
                    },
                    "error": {
                      "example": "Invalid font size value",
                      "type": "string"
                    },
                    "fieldErrors": {
                      "additionalProperties": {
                        "items": {
                          "type": "string"
                        },
                        "type": "array"
                      },
                      "example": {
                        "font_size": [
                          "font_size must be a valid enum value"
                        ]
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid configuration values"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "PROFILE_NOT_FOUND",
                      "type": "string"
                    },
                    "error": {
                      "example": "User profile not found",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "User profile not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update document viewer configuration",
        "tags": [
          "User Profile"
        ]
      }
    },
    "/user-profile/journal-context-presets": {
      "get": {
        "description": "Retrieve all journal context presets for the authenticated user.\n\n## Use Case\nJournal context presets store frequently used context information for AI-assisted transaction categorization.\nUsers can quickly apply pre-saved context when analyzing transactions.\n\n## Example Presets\n- **不動産管理**: Context for property management expenses\n- **システム開発**: Context for software development projects\n- **海外出張**: Context for international business travel\n\n## Response\nReturns an array of presets with:\n- **id**: Unique preset identifier\n- **label**: Display name (Japanese)\n- **context**: Full context text for AI\n- **createdAt/updatedAt**: Timestamps\n\n## Limits\n- Maximum 10 presets per user\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "empty": {
                    "summary": "User with no presets",
                    "value": {
                      "data": [],
                      "message": "Journal context presets retrieved successfully",
                      "statusCode": 200
                    }
                  },
                  "with_presets": {
                    "summary": "User with saved presets",
                    "value": {
                      "data": [
                        {
                          "context": "この取引は軽井沢別荘の管理運営に関連しています。固定資産関連の経費として処理してください。",
                          "createdAt": "2026-01-15T10:30:00.000Z",
                          "id": "preset-1",
                          "label": "不動産管理",
                          "updatedAt": "2026-01-15T10:30:00.000Z"
                        },
                        {
                          "context": "顧客向けシステム開発プロジェクトの費用です。外注費または研究開発費として処理してください。",
                          "createdAt": "2026-01-15T11:00:00.000Z",
                          "id": "preset-2",
                          "label": "システム開発",
                          "updatedAt": "2026-01-15T11:00:00.000Z"
                        }
                      ],
                      "message": "Journal context presets retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/JournalContextPresetsResponse"
                }
              }
            },
            "description": "Journal context presets retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "PROFILE_NOT_FOUND",
                      "type": "string"
                    },
                    "error": {
                      "example": "User profile not found",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "User profile not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get journal context presets (補足情報プリセット取得)",
        "tags": [
          "User Profile"
        ]
      },
      "post": {
        "description": "Create a new preset or update an existing one by ID.\n\n## Behavior\n- If preset with given ID exists: Updates the preset\n- If preset with given ID does not exist: Creates new preset\n\n## Limits\n- Maximum 10 presets per user (error if limit exceeded on create)\n- Label and context are sanitized for security\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "create_new": {
                  "summary": "Create new preset",
                  "value": {
                    "context": "マーケティングキャンペーンに関連する広告宣伝費です",
                    "id": "preset-new-1",
                    "label": "広告宣伝"
                  }
                },
                "update_existing": {
                  "summary": "Update existing preset",
                  "value": {
                    "context": "この取引は軽井沢別荘と箱根保養所の管理運営に関連しています",
                    "id": "preset-1",
                    "label": "不動産管理（更新）"
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/UpsertJournalContextPresetRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/JournalContextPresetsResponse"
                }
              }
            },
            "description": "Preset created or updated successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "VALIDATION_ERROR",
                      "type": "string"
                    },
                    "error": {
                      "example": "Maximum 10 presets allowed",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Validation error or maximum presets exceeded"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Create or update a single preset (補足情報プリセット追加/更新)",
        "tags": [
          "User Profile"
        ]
      },
      "put": {
        "description": "Replace all journal context presets with a new array.\n\n## Use Case\nFull replacement of all presets. Use when syncing from frontend localStorage to backend.\n\n## Request Body\nArray of presets to replace existing ones. Timestamps are automatically added/updated.\n\n## Limits\n- Maximum 10 presets per user\n- Label and context are sanitized for security\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "clear_all": {
                  "summary": "Clear all presets",
                  "value": {
                    "journalContextPresets": []
                  }
                },
                "replace_all": {
                  "summary": "Replace all presets",
                  "value": {
                    "journalContextPresets": [
                      {
                        "context": "この取引は軽井沢別荘の管理運営に関連しています",
                        "id": "preset-1",
                        "label": "不動産管理"
                      },
                      {
                        "context": "顧客向けシステム開発プロジェクトの費用です",
                        "id": "preset-2",
                        "label": "システム開発"
                      },
                      {
                        "context": "海外出張に関連する経費です。旅費交通費として処理してください。",
                        "id": "preset-3",
                        "label": "海外出張"
                      }
                    ]
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/UpdateJournalContextPresetsRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/JournalContextPresetsResponse"
                }
              }
            },
            "description": "Journal context presets updated successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "VALIDATION_ERROR",
                      "type": "string"
                    },
                    "error": {
                      "example": "Maximum 10 presets allowed",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Validation error or maximum presets exceeded"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Replace all journal context presets (補足情報プリセット全置換)",
        "tags": [
          "User Profile"
        ]
      }
    },
    "/user-profile/journal-context-presets/{presetId}": {
      "delete": {
        "description": "Delete a specific journal context preset by ID.\n\n## Behavior\nRemoves the preset with the given ID from the user's preset list.\nReturns 404 if preset not found.\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "ID of the preset to delete",
            "example": "preset-1",
            "in": "path",
            "name": "presetId",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "success": {
                    "summary": "Remaining presets after deletion",
                    "value": {
                      "data": [
                        {
                          "context": "顧客向けシステム開発プロジェクトの費用です",
                          "createdAt": "2026-01-15T11:00:00.000Z",
                          "id": "preset-2",
                          "label": "システム開発",
                          "updatedAt": "2026-01-15T11:00:00.000Z"
                        }
                      ],
                      "message": "Preset deleted successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/JournalContextPresetsResponse"
                }
              }
            },
            "description": "Preset deleted successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "NOT_FOUND",
                      "type": "string"
                    },
                    "error": {
                      "example": "Preset not found",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Preset not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Delete a journal context preset (補足情報プリセット削除)",
        "tags": [
          "User Profile"
        ]
      }
    },
    "/user-profile/preferences": {
      "get": {
        "description": "Retrieve the complete user preferences including AI provider configurations and document viewer settings.\n\n## Response Data\nReturns comprehensive user preferences with:\n- **AI Provider Settings**: Configuration for OpenAI, Claude, and Together AI\n- **Document Viewer Config**: Typography, layout, visual, and print preferences\n- **Security**: API keys are automatically masked in responses\n- **Personalization**: User-specific customization and accessibility settings\n\n## AI Provider Configuration\nSupports multiple AI providers:\n- **OpenAI**: GPT models and API configuration\n- **Claude**: Anthropic's Claude models and settings\n- **Together AI**: Open-source model hosting platform\n\n## Document Viewer Customization\nComprehensive display preferences:\n- **Typography**: Font size and family optimized for Japanese content\n- **Layout**: Density, width constraints, and line number display\n- **Visual**: Color schemes, borders, shadows, and accessibility options\n- **Print**: Optimized settings for document printing\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "complete_preferences": {
                    "summary": "Complete user preferences with all configurations",
                    "value": {
                      "data": {
                        "documentViewerConfig": {
                          "color_scheme": 0,
                          "document_style_variant": 0,
                          "font_family": 0,
                          "font_size": 2,
                          "layout_density": 1,
                          "max_width": 1,
                          "print_color_scheme": 1,
                          "print_font_size": 1,
                          "selected_preset_id": "preset-wabi",
                          "show_borders": true,
                          "show_line_numbers": false,
                          "show_shadows": true
                        },
                        "preferences": {
                          "claude": {
                            "api_key": "****************",
                            "is_active": false,
                            "model": "claude-3-opus-20240229"
                          },
                          "openai": {
                            "api_key": "****************",
                            "is_active": true,
                            "model": "gpt-4"
                          },
                          "together": {
                            "api_key": "****************",
                            "is_active": false,
                            "model": "meta-llama/Llama-2-70b-chat-hf"
                          },
                          "tour_completion": {
                            "bank_statement_tour": {
                              "completed": false
                            },
                            "homepage_tour": {
                              "completed": true,
                              "completedAt": "2026-01-30T20:44:00.000Z"
                            },
                            "welcome_guide": {
                              "completed": true,
                              "completedAt": "2026-01-30T20:30:00.000Z"
                            }
                          }
                        }
                      },
                      "message": "User preferences retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/UserPreferencesResponse"
                }
              }
            },
            "description": "User preferences retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "PROFILE_NOT_FOUND",
                      "type": "string"
                    },
                    "error": {
                      "example": "User profile not found",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "User profile not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get user preferences",
        "tags": [
          "User Profile"
        ]
      },
      "put": {
        "description": "Update user preferences with deep merge strategy preserving existing configurations.\n\n## Request Body\nAll fields are optional for partial updates:\n- **preferences**: AI provider configurations (OpenAI, Claude, Together)\n- **documentViewerConfig**: Document viewer display settings\n- **tour_completion**: Tour/guide completion status tracking\n\n## Tour Completion Tracking\nTracks which onboarding tours the user has completed:\n- `welcome_guide`: Initial welcome experience\n- `homepage_tour`: Homepage feature tour\n- `bank_statement_tour`: Bank statement management tour\n- `settings_tour`: Settings page tour\n- And more page-specific tours...\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "ai_preferences_only": {
                  "summary": "Update only AI provider preferences",
                  "value": {
                    "preferences": {
                      "claude": {
                        "is_active": false
                      },
                      "openai": {
                        "api_key": "sk-proj-abc123...",
                        "is_active": true,
                        "model": "gpt-4-turbo"
                      }
                    }
                  }
                },
                "complete_update": {
                  "summary": "Update both AI preferences and document viewer",
                  "value": {
                    "documentViewerConfig": {
                      "color_scheme": 3,
                      "font_family": 2,
                      "font_size": 2,
                      "print_color_scheme": 1,
                      "show_line_numbers": true
                    },
                    "preferences": {
                      "openai": {
                        "is_active": true,
                        "model": "gpt-4"
                      }
                    }
                  }
                },
                "document_viewer_only": {
                  "summary": "Update only document viewer configuration",
                  "value": {
                    "documentViewerConfig": {
                      "color_scheme": 2,
                      "font_family": 1,
                      "font_size": 3,
                      "layout_density": 2
                    }
                  }
                },
                "multiple_tours_completed": {
                  "summary": "Mark multiple tours as completed",
                  "value": {
                    "tour_completion": {
                      "bank_statement_tour": {
                        "completed": true,
                        "completedAt": "2026-01-30T21:00:00.000Z"
                      },
                      "homepage_tour": {
                        "completed": true,
                        "completedAt": "2026-01-30T20:44:00.000Z"
                      },
                      "welcome_guide": {
                        "completed": true,
                        "completedAt": "2026-01-30T20:30:00.000Z"
                      }
                    }
                  }
                },
                "tour_completion_update": {
                  "summary": "Mark a tour as completed",
                  "value": {
                    "tour_completion": {
                      "homepage_tour": {
                        "completed": true,
                        "completedAt": "2026-01-30T20:44:00.000Z"
                      }
                    }
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/UpdateUserPreferencesRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/UserPreferencesUpdateResponse"
                }
              }
            },
            "description": "User preferences updated successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "VALIDATION_ERROR",
                      "type": "string"
                    },
                    "error": {
                      "example": "Invalid font size value",
                      "type": "string"
                    },
                    "fieldErrors": {
                      "additionalProperties": {
                        "items": {
                          "type": "string"
                        },
                        "type": "array"
                      },
                      "example": {
                        "documentViewerConfig.font_size": [
                          "font_size must be a valid enum value"
                        ]
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid preference values or validation errors"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "PROFILE_NOT_FOUND",
                      "type": "string"
                    },
                    "error": {
                      "example": "User profile not found",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "User profile not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update user preferences",
        "tags": [
          "User Profile"
        ]
      }
    },
    "/user-profile/ui-preferences": {
      "get": {
        "description": "Returns the user's mobile/native UI preferences (density, dock pin, table layouts, font scale, reduced motion). Empty rows return the default contract so the FE can hydrate without null checks.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "defaults": {
                    "summary": "New user — server returns defaults",
                    "value": {
                      "data": {
                        "density": "default",
                        "dock_pin": [],
                        "font_scale": 1,
                        "reduced_motion": false,
                        "table_layouts": {}
                      },
                      "message": "UI preferences retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/UiPreferencesResponse"
                }
              }
            },
            "description": "UI preferences retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get cross-device UI preferences",
        "tags": [
          "User Profile"
        ]
      },
      "patch": {
        "description": "Shallow-merges the provided keys with the existing JSON. `table_layouts` is also shallow-merged so individual entries can be cleared by sending `null`. Unknown keys are rejected.",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "clear_table": {
                  "summary": "Clear an override (revert to auto)",
                  "value": {
                    "table_layouts": {
                      "tax-journal.entries": null
                    }
                  }
                },
                "pin_density": {
                  "summary": "Pin two dock items + bump density on mobile",
                  "value": {
                    "density": "ultra",
                    "dock_pin": [
                      "scan",
                      "documents"
                    ]
                  }
                },
                "table_override": {
                  "summary": "Override a single table to scroll-frozen",
                  "value": {
                    "table_layouts": {
                      "tax-journal.entries": "scroll-frozen"
                    }
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/UpdateUiPreferencesRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/UiPreferencesResponse"
                }
              }
            },
            "description": "UI preferences updated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Patch cross-device UI preferences",
        "tags": [
          "User Profile"
        ]
      }
    },
    "/user/accounting-config": {
      "get": {
        "description": "Retrieve the complete accounting configuration for the authenticated user with Japanese tax compliance settings.\n\n## Configuration Overview\nReturns comprehensive Japanese accounting configuration including:\n- **Tax Declaration Type**: Blue Tax (青色申告) vs White Tax (白色申告) selection\n- **Consumption Tax Method**: Various calculation methods including the new 2割特例\n- **Taxation Type**: Individual, proportional, simplified, or exempt classifications\n- **Accounting Method**: Tax-inclusive vs tax-exclusive accounting\n- **Depreciation Method**: Japanese standard depreciation calculation methods\n- **Special Provisions**: Tax payment deferrals and exemption periods\n\n## Japanese Tax Declaration Types\n- **Blue Tax (青色申告)**: Advanced tax filing with additional deductions and benefits\n- **White Tax (白色申告)**: Standard tax filing for simpler business structures\n\n## Consumption Tax Methods\n- **General Method (一般課税方式)**: Standard method with actual input tax calculation\n- **Simplified Method (簡易課税方式)**: Simplified method using deemed input rate by industry\n- **Special 20% Method (特例20%課税方式)**: Legacy special 20% deemed expense method\n- **Two-Percent Special Rule (2割特例)**: Available Oct 2023 - Sep 2026 for newly registered Invoice System businesses\n\n## Taxation Types\n- **General Individual (一般個人)**: Standard individual taxation\n- **General Proportional (一般比例)**: Proportional tax calculation\n- **Simplified (簡易)**: Simplified taxation method\n- **Exempt (免税)**: Tax-exempt status\n\n## Accounting Methods\n- **Tax Exclusive (税抜)**: Prices recorded excluding consumption tax\n- **Tax Inclusive (税込)**: Prices recorded including consumption tax\n\n## Depreciation Methods\n- **Straight Line (定額法)**: Equal annual depreciation\n- **Declining Balance (定率法)**: Accelerated depreciation method\n- **Old Straight Line (旧定額法)**: Legacy straight-line method\n- **Old Declining Balance (旧定率法)**: Legacy declining balance method\n\n## Default Configuration\nIf no configuration exists, a default configuration is automatically created with standard Japanese accounting settings.\n\n## Compliance Features\n- Aligned with Japanese National Tax Agency (NTA) regulations\n- Supports Invoice System (インボイス制度) requirements\n- Handles special tax periods and exemptions\n- Maintains audit trail for tax compliance\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "examples": {
                  "blue_tax_general": {
                    "summary": "Blue Tax with General Consumption Tax Method",
                    "value": {
                      "data": {
                        "accounting_method": 0,
                        "consumption_tax_method": 0,
                        "created_at": "2024-01-15T10:30:00.000Z",
                        "declaration_type": 0,
                        "depreciation_method": 1,
                        "has_exempt_period": false,
                        "has_tax_payment_special_provision": false,
                        "id": "123e4567-e89b-12d3-a456-426614174000",
                        "is_deleted": false,
                        "tax_calculation": 0,
                        "taxation_type": 0,
                        "updated_at": "2024-01-15T10:30:00.000Z",
                        "user_id": "789e0123-e45b-67c8-d901-234567890123"
                      },
                      "message": "Accounting config retrieved successfully",
                      "statusCode": 200
                    }
                  },
                  "two_percent_special": {
                    "summary": "Configuration with Two-Percent Special Rule",
                    "value": {
                      "data": {
                        "accounting_method": 1,
                        "consumption_tax_method": 3,
                        "created_at": "2024-01-15T10:30:00.000Z",
                        "declaration_type": 0,
                        "depreciation_method": 2,
                        "has_exempt_period": true,
                        "has_tax_payment_special_provision": false,
                        "id": "456e7890-f12a-34b5-c678-901234567890",
                        "is_deleted": false,
                        "tax_calculation": 0,
                        "taxation_type": 0,
                        "updated_at": "2024-01-15T10:30:00.000Z",
                        "user_id": "789e0123-e45b-67c8-d901-234567890123"
                      },
                      "message": "Accounting config retrieved successfully",
                      "statusCode": 200
                    }
                  }
                },
                "schema": {
                  "$ref": "#/components/schemas/AccountingConfigResponse"
                }
              }
            },
            "description": "Accounting configuration retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get user accounting configuration",
        "tags": [
          "User Accounting Config"
        ]
      },
      "put": {
        "description": "Update the accounting configuration with Japanese tax compliance validation and enum checking.\n\n## Request Body\nAll fields are optional for partial updates:\n- **declaration_type**: Tax declaration method selection\n- **consumption_tax_method**: Consumption tax calculation approach\n- **taxation_type**: Business taxation classification\n- **accounting_method**: Tax inclusion preference\n- **depreciation_method**: Asset depreciation calculation\n- **Special provisions**: Tax deferrals and exemption settings\n\n## Update Behavior\n- **Partial Updates**: Only provided fields are updated\n- **Enum Validation**: All values validated against Japanese tax standards\n- **Compliance Checking**: Ensures configuration meets NTA requirements\n- **Atomic Updates**: Changes applied in database transactions\n- **Audit Logging**: All changes logged for compliance tracking\n\n## Japanese Tax Compliance\nConfiguration updates must comply with:\n- **National Tax Agency (NTA) regulations**\n- **Invoice System (インボイス制度) requirements**\n- **Consumption tax law updates**\n- **Corporate and individual tax standards**\n- **Depreciation calculation rules**\n\n## Declaration Type Selection\n- **Blue Tax (青色申告)**: \n  - Requires detailed bookkeeping\n  - Allows special deductions (最大65万円控除)\n  - Supports loss carryforward (欠損金の繰越)\n  - Enables family employee salary deductions\n  \n- **White Tax (白色申告)**:\n  - Simplified bookkeeping requirements\n  - Standard deductions only\n  - Limited tax benefits\n  - Suitable for smaller businesses\n\n## Consumption Tax Method Details\n- **General Method (一般課税方式)**:\n  - Calculate actual input tax\n  - Suitable for businesses with significant input tax\n  - Requires detailed tax records\n  \n- **Simplified Method (簡易課税方式)**:\n  - Uses deemed input rate by industry type\n  - Available for businesses with sales ≤ 50 million yen\n  - Reduces administrative burden\n  \n- **Two-Percent Special Rule (2割特例)**:\n  - Available: October 2023 - September 2026\n  - For newly registered Invoice System businesses\n  - Tax = Sales Tax × 80% (effectively 2% of sales)\n  - Transitional measure for small businesses\n\n## Taxation Type Classifications\n- **General Individual**: Standard individual business taxation\n- **General Proportional**: Proportional tax rate application\n- **Simplified**: Reduced compliance requirements for small businesses\n- **Exempt**: Tax-exempt status for qualifying entities\n\n## Depreciation Method Selection\nChoose appropriate method based on:\n- **Asset type and usage patterns**\n- **Tax optimization strategy**\n- **Cash flow considerations**\n- **Regulatory requirements**\n\n## Validation Rules\n- All enum values must match Japanese tax standards\n- Consumption tax method must be valid for business size\n- Declaration type must align with bookkeeping capabilities\n- Depreciation method must be appropriate for asset types\n- Special provisions require eligibility verification\n\n## Use Cases\n- **New Business Setup**: Configure initial tax compliance settings\n- **Tax Method Changes**: Update methods based on business growth\n- **Compliance Updates**: Align with new tax regulations\n- **Optimization**: Adjust settings for tax efficiency\n- **Audit Preparation**: Ensure proper configuration for tax audits\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "examples": {
                "blue_tax_setup": {
                  "summary": "Configure Blue Tax with General Method",
                  "value": {
                    "accounting_method": 0,
                    "consumption_tax_method": 0,
                    "declaration_type": 0,
                    "depreciation_method": 1,
                    "has_exempt_period": false,
                    "taxation_type": 0
                  }
                },
                "simplified_method": {
                  "summary": "Configure Simplified Consumption Tax",
                  "value": {
                    "accounting_method": 0,
                    "consumption_tax_method": 1,
                    "depreciation_method": 2
                  }
                },
                "two_percent_special_setup": {
                  "summary": "Configure Two-Percent Special Rule",
                  "value": {
                    "accounting_method": 1,
                    "consumption_tax_method": 3,
                    "declaration_type": 0,
                    "has_exempt_period": true,
                    "taxation_type": 0
                  }
                },
                "white_tax_basic": {
                  "summary": "Basic White Tax Configuration",
                  "value": {
                    "accounting_method": 1,
                    "consumption_tax_method": 0,
                    "declaration_type": 1,
                    "tax_calculation": 1,
                    "taxation_type": 2
                  }
                }
              },
              "schema": {
                "$ref": "#/components/schemas/UpdateAccountingConfigRequest"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AccountingConfigUpdateResponse"
                }
              }
            },
            "description": "Accounting configuration updated successfully"
          },
          "400": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "VALIDATION_ERROR",
                      "type": "string"
                    },
                    "error": {
                      "example": "Invalid consumption tax method",
                      "type": "string"
                    },
                    "fieldErrors": {
                      "additionalProperties": {
                        "items": {
                          "type": "string"
                        },
                        "type": "array"
                      },
                      "example": {
                        "consumption_tax_method": [
                          "Invalid consumption tax method"
                        ]
                      },
                      "type": "object"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Invalid configuration values or validation errors"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "code": {
                      "example": "CONFIG_NOT_FOUND",
                      "type": "string"
                    },
                    "error": {
                      "example": "Accounting configuration not found",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "User accounting configuration not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Update user accounting configuration",
        "tags": [
          "User Accounting Config"
        ]
      }
    },
    "/year-close/questions/{question_key}/acknowledge": {
      "post": {
        "description": "修正の必要がない理由を8文字以上で記録します（`OQ:<key>` の確認記録）。理由は当社の回答として確認事項のやり取りにも追記されます。",
        "parameters": [
          {
            "in": "path",
            "name": "question_key",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "reason": {
                    "maxLength": 2000,
                    "minLength": 8,
                    "type": "string"
                  }
                },
                "required": [
                  "reason"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "checkRule": {
                          "type": "string"
                        },
                        "id": {
                          "format": "uuid",
                          "type": "string"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "記録した"
          },
          "400": {
            "description": "入力不正"
          },
          "401": {
            "description": "未認証"
          },
          "404": {
            "description": "確認事項が存在しない"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "確認事項を理由つきで確認する",
        "tags": [
          "Year close"
        ]
      }
    },
    "/year-close/{fiscal_year}/gate": {
      "get": {
        "description": "記録済みの確認事項から判定します（書き込みなし）。",
        "parameters": [
          {
            "in": "path",
            "name": "fiscal_year",
            "required": true,
            "schema": {
              "example": 2025,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "$ref": "#/components/schemas/YearCloseGate"
                    },
                    "message": {
                      "type": "string"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "判定"
          },
          "400": {
            "description": "年度が不正"
          },
          "401": {
            "description": "未認証"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "決算確定・申告書を止めている確認事項",
        "tags": [
          "Year close"
        ]
      }
    },
    "/year-close/{fiscal_year}/override": {
      "post": {
        "description": "税理士に SBC の外で確認した内容を10文字以上で記録し、いま止めている確認事項に限って決算確定・申告書の作成を続行できるようにします。記録は取消できますが削除されません（finding_acknowledgments）。",
        "parameters": [
          {
            "in": "path",
            "name": "fiscal_year",
            "required": true,
            "schema": {
              "example": 2025,
              "type": "integer"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "note": {
                    "maxLength": 2000,
                    "minLength": 10,
                    "type": "string"
                  }
                },
                "required": [
                  "note"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "coveredKeys": {
                          "items": {
                            "type": "string"
                          },
                          "type": "array"
                        },
                        "id": {
                          "format": "uuid",
                          "type": "string"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "記録した"
          },
          "400": {
            "description": "入力不正"
          },
          "401": {
            "description": "未認証"
          },
          "409": {
            "description": "未解決の確認事項がない"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "税理士に確認済みとして続行（監査記録）",
        "tags": [
          "Year close"
        ]
      }
    },
    "/year-close/{fiscal_year}/recheck": {
      "post": {
        "description": "年度を対象にした整合性チェック（comprehensive）を実行し、その結果で確認事項を登録・更新します。1ユーザーにつき同時に1件、前回の実行から60秒は 429（Retry-After / details.retry_after_seconds）。",
        "parameters": [
          {
            "in": "path",
            "name": "fiscal_year",
            "required": true,
            "schema": {
              "example": 2025,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "gate": {
                          "$ref": "#/components/schemas/YearCloseGate"
                        },
                        "sync": {
                          "properties": {
                            "complete": {
                              "description": "false = 一部しか読めなかった（差替えはしていない）",
                              "type": "boolean"
                            },
                            "filed": {
                              "type": "integer"
                            },
                            "fiscalYear": {
                              "type": "integer"
                            },
                            "reopened": {
                              "type": "integer"
                            },
                            "superseded": {
                              "type": "integer"
                            },
                            "updated": {
                              "type": "integer"
                            }
                          },
                          "type": "object"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "登録結果と判定"
          },
          "400": {
            "description": "年度が不正"
          },
          "401": {
            "description": "未認証"
          },
          "429": {
            "description": "実行中、または前回の実行から60秒以内（ERR_8001）"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "整合性チェックをその年度で再実行して確認事項を更新する",
        "tags": [
          "Year close"
        ]
      }
    },
    "/year-close/{fiscal_year}/sync": {
      "post": {
        "description": "帳簿アドバイス（books-advisor）と整合性チェックの指摘を、安定キーで確認事項に登録・更新します。税理士の回答は上書きしません。検出されなくなった指摘の確認事項は「差替え」になります。",
        "parameters": [
          {
            "in": "path",
            "name": "fiscal_year",
            "required": true,
            "schema": {
              "example": 2025,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "data": {
                      "properties": {
                        "gate": {
                          "$ref": "#/components/schemas/YearCloseGate"
                        },
                        "sync": {
                          "properties": {
                            "complete": {
                              "description": "false = 一部しか読めなかった（差替えはしていない）",
                              "type": "boolean"
                            },
                            "filed": {
                              "type": "integer"
                            },
                            "fiscalYear": {
                              "type": "integer"
                            },
                            "reopened": {
                              "type": "integer"
                            },
                            "superseded": {
                              "type": "integer"
                            },
                            "updated": {
                              "type": "integer"
                            }
                          },
                          "type": "object"
                        }
                      },
                      "type": "object"
                    },
                    "message": {
                      "type": "string"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "登録結果と判定"
          },
          "400": {
            "description": "年度が不正"
          },
          "401": {
            "description": "未認証"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "その年度の指摘を確認事項として登録する",
        "tags": [
          "Year close"
        ]
      }
    },
    "/year-end-adjustment/calculate": {
      "post": {
        "description": "Perform comprehensive year-end tax adjustment calculation for all employees.\n\n## Year-end Adjustment Calculation (年末調整計算)\nComprehensive tax adjustment processing with:\n- **Income Aggregation**: Aggregate annual salary and bonus payments from pay slip data\n- **Deduction Processing**: Calculate all applicable tax deductions for each employee\n- **Progressive Tax Calculation**: Apply Japanese income tax brackets (5% to 45%)\n- **Tax Credit Application**: Apply housing loan tax credits and other applicable credits\n- **Adjustment Calculation**: Calculate over/under payment amounts for each employee\n- **Company Summary**: Generate company-wide summary with totals and statistics\n\n## Calculation Process\n1. **Data Aggregation**: Collect pay slip data for the fiscal year\n2. **Income Calculation**: Calculate gross income and salary income deduction\n3. **Deduction Processing**: Process all deduction types with validation\n4. **Taxable Income**: Calculate taxable income after all deductions\n5. **Tax Calculation**: Apply progressive tax brackets and calculate tax due\n6. **Credit Application**: Apply tax credits (housing loan, etc.)\n7. **Adjustment Calculation**: Compare withheld tax vs. calculated tax\n8. **Result Generation**: Generate detailed results for each employee and company summary\n\n## Deduction Types\n- **Basic Deduction (基礎控除)**: Standard deduction for all employees\n- **Spouse Deduction (配偶者控除)**: Deduction for spouse with low income\n- **Dependent Deduction (扶養控除)**: Deduction for dependent family members\n- **Social Insurance (社会保険料控除)**: Health insurance, pension, employment insurance\n- **Life Insurance (生命保険料控除)**: Life, nursing care, and personal pension insurance\n- **Earthquake Insurance (地震保険料控除)**: Earthquake insurance premiums\n- **Housing Loan Credit (住宅借入金等特別控除)**: Tax credit for housing loans\n- **Small Business Mutual Aid (小規模企業共済等掛金控除)**: Small business mutual aid contributions\n- **iDeCo Contributions**: Individual defined contribution pension plan\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "properties": {
                  "employee_deductions": {
                    "additionalProperties": {
                      "$ref": "#/components/schemas/EmployeeDeductionInput"
                    },
                    "description": "Employee-specific deduction amounts (optional)",
                    "example": {
                      "田中太郎": {
                        "dependent_deduction": 380000,
                        "earthquake_insurance_deduction": 25000,
                        "housing_loan_deduction": 210000,
                        "ideco_deduction": 276000,
                        "new_life_insurance": 80000,
                        "nursing_insurance": 20000,
                        "small_business_mutual_aid_deduction": 120000,
                        "spouse_deduction": 380000
                      }
                    },
                    "type": "object"
                  },
                  "fiscal_year": {
                    "description": "Fiscal year for year-end adjustment",
                    "example": 2024,
                    "type": "integer"
                  }
                },
                "required": [
                  "fiscal_year"
                ],
                "type": "object"
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/YearEndCalculationResponse"
                }
              }
            },
            "description": "Year-end adjustment calculation completed successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Calculate year-end adjustment for all employees (年末調整計算)",
        "tags": [
          "Year-end Adjustment"
        ]
      }
    },
    "/year-end-adjustment/checklist": {
      "get": {
        "description": "Get comprehensive deduction checklist for year-end adjustment preparation.\n\n## Deduction Checklist (控除チェックリスト)\nComprehensive preparation guide with:\n- **Deduction Categories**: Organized by deduction type and category\n- **Required Documents**: Complete list of required supporting documents\n- **Amount Limits**: Maximum deduction amounts and calculation rules\n- **Deadlines**: Important deadlines for document submission and processing\n- **Compliance Notes**: Important compliance considerations and requirements\n\n## Checklist Categories\n- **Personal Deductions (本人に関する控除)**: Basic deduction and personal allowances\n- **Family Deductions (家族に関する控除)**: Spouse and dependent deductions\n- **Insurance Deductions (保険料控除)**: Social insurance, life insurance, earthquake insurance\n- **Other Deductions (その他の控除)**: Small business mutual aid, housing loan credits\n\n## Document Requirements\n- **Submission Deadlines**: Clear deadlines for each type of document\n- **Required Formats**: Specific format requirements for supporting documents\n- **Verification Process**: Document verification and validation procedures\n- **Missing Document Handling**: Procedures for handling missing or incomplete documents\n\n## Use Cases\n- **Employee Guidance**: Guide employees through deduction preparation\n- **HR Processing**: Support HR teams in year-end adjustment processing\n- **Compliance Management**: Ensure compliance with documentation requirements\n- **Training Material**: Use as training material for year-end adjustment procedures\n- **Process Standardization**: Standardize year-end adjustment processes\n\nRequires a JWT. Default-deny at /api does not treat this path as public.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DeductionChecklistResponse"
                }
              }
            },
            "description": "Deduction checklist retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get deduction checklist (控除チェックリスト)",
        "tags": [
          "Year-end Adjustment"
        ]
      }
    },
    "/year-end-adjustment/employee/{name}": {
      "get": {
        "description": "Get detailed year-end adjustment results for a specific employee.\n\n## Individual Employee Details (従業員個別詳細)\nComprehensive employee-specific information with:\n- **Income Breakdown**: Detailed salary and bonus breakdown\n- **Deduction Details**: All deduction amounts and calculations\n- **Tax Calculation**: Step-by-step tax calculation process\n- **Adjustment Analysis**: Detailed adjustment amount calculation\n- **Supporting Data**: All supporting data for verification\n\n## Detailed Information\n- **Annual Income**: Total salary, bonus, and gross income amounts\n- **Salary Income Deduction**: Calculated salary income deduction based on income level\n- **All Deductions**: Breakdown of all deduction types and amounts\n- **Taxable Income**: Final taxable income after all deductions\n- **Tax Calculation**: Progressive tax calculation with applicable rates\n- **Tax Credits**: Housing loan and other tax credit applications\n- **Final Adjustment**: Over/under payment calculation and adjustment type\n\n## Use Cases\n- **Employee Inquiry**: Answer employee questions about their year-end adjustment\n- **Verification**: Verify calculation accuracy for specific employees\n- **Documentation**: Generate detailed documentation for employee records\n- **Audit Support**: Provide detailed information for tax audits\n- **Correction Processing**: Support correction of calculation errors\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Employee name (URL encoded)",
            "example": "田中太郎",
            "in": "path",
            "name": "name",
            "required": true,
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "Fiscal year for employee details",
            "in": "query",
            "name": "fiscal_year",
            "required": true,
            "schema": {
              "example": 2024,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/EmployeeDetailsResponse"
                }
              }
            },
            "description": "Employee details retrieved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "message": {
                      "example": "従業員が見つかりません",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Employee not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get individual employee year-end details (従業員個別詳細)",
        "tags": [
          "Year-end Adjustment"
        ]
      }
    },
    "/year-end-adjustment/health": {
      "get": {
        "description": "Check the health and availability of the Year-end Tax Adjustment API.\n\n## Health Check Features\nAPI health monitoring with:\n- **Service Status**: Verify API service availability\n- **Feature Overview**: List available year-end adjustment processing features\n- **System Information**: Basic system health information\n- **Tax Calculation Readiness**: Verify tax calculation system readiness\n\n## Available Features\n- **Annual Income Aggregation (給与・賞与集計)**: Aggregate salary and bonus payments for the fiscal year\n- **Deduction Calculation (各種控除)**: Calculate all types of tax deductions including basic, spouse, dependent, and insurance deductions\n- **Income Tax Calculation (所得税計算)**: Progressive income tax calculation using Japanese tax brackets\n- **Over/Under Payment Calculation (過不足税額)**: Calculate tax adjustment amounts for refunds or additional collections\n- **Withholding Slip Generation (源泉徴収票)**: Generate official withholding tax slip data\n\n## Use Cases\n- **System Monitoring**: Monitor API health and availability\n- **Feature Discovery**: Discover available year-end adjustment features\n- **Integration Testing**: Test API connectivity and basic functionality\n- **Service Verification**: Verify service is ready for year-end processing\n\nRequires a JWT. Default-deny at /api does not treat this path as public.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/YearEndAdjustmentHealthResponse"
                }
              }
            },
            "description": "API health check successful"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Health check for Year-end Adjustment API",
        "tags": [
          "Year-end Adjustment"
        ]
      }
    },
    "/year-end-adjustment/reference/tax-brackets": {
      "get": {
        "description": "Get reference information for Japanese income tax brackets.\n\n## Tax Bracket Reference (税率区分参照)\nComprehensive tax bracket information with:\n- **Progressive Tax Rates**: Complete Japanese income tax bracket system\n- **Rate Calculations**: Tax rates from 5% to 45% with specific thresholds\n- **Deduction Amounts**: Tax deduction amounts for each bracket\n- **Calculation Formula**: Official formula for tax calculation\n- **Special Taxes**: Information about reconstruction special income tax\n\n## Tax Bracket System\n- **Seven Brackets**: Progressive tax system with seven income brackets\n- **Rate Range**: Tax rates from 5% (lowest bracket) to 45% (highest bracket)\n- **Threshold Amounts**: Specific income thresholds for each bracket\n- **Deduction Calculations**: Simplified calculation using deduction amounts\n- **Progressive Structure**: Higher rates apply only to income above thresholds\n\n## Calculation Method\n- **Formula**: 税額 = 課税所得金額 × 税率 - 控除額\n- **Progressive Application**: Each bracket applies only to income within that range\n- **Deduction Method**: Use deduction amounts for simplified calculation\n- **Reconstruction Tax**: Additional 2.1% reconstruction special income tax\n- **Rounding Rules**: Official rounding rules for tax calculations\n\n## Use Cases\n- **Tax Education**: Educate employees about tax calculation methods\n- **Calculation Verification**: Verify tax calculation accuracy\n- **Planning Support**: Support tax planning and income optimization\n- **System Development**: Reference for tax calculation system development\n- **Compliance Training**: Training material for tax compliance\n\nRequires a JWT. Default-deny at /api does not treat this path as public.",
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/TaxBracketReferenceResponse"
                }
              }
            },
            "description": "Tax bracket reference retrieved successfully"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get tax bracket reference (税率区分参照)",
        "tags": [
          "Year-end Adjustment"
        ]
      }
    },
    "/year-end-adjustment/summary": {
      "get": {
        "description": "Get year-end adjustment summary without recalculating.\n\n## Year-end Adjustment Summary (年末調整サマリー)\nComprehensive summary information with:\n- **Employee Overview**: Summary information for all employees\n- **Company Totals**: Aggregated totals for the entire company\n- **Adjustment Statistics**: Statistics on refunds and additional collections\n- **Processing Status**: Information about calculation completion\n- **Quick Reference**: Key figures for management reporting\n\n## Summary Information\n- **Employee Count**: Total number of employees processed\n- **Income Totals**: Total gross income for all employees\n- **Tax Calculations**: Total calculated tax and withheld tax amounts\n- **Adjustment Amounts**: Total refund and additional collection amounts\n- **Employee Breakdown**: Individual employee summary with adjustment types\n\n## Use Cases\n- **Management Reporting**: Quick overview for management decisions\n- **Payroll Planning**: Plan payroll adjustments for the next period\n- **Cash Flow Management**: Understand cash flow impact of adjustments\n- **Compliance Monitoring**: Monitor completion of year-end processing\n- **Employee Communication**: Prepare employee communications about adjustments\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Fiscal year for summary",
            "in": "query",
            "name": "fiscal_year",
            "required": true,
            "schema": {
              "example": 2024,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/YearEndSummaryResponse"
                }
              }
            },
            "description": "Year-end adjustment summary retrieved successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Get year-end adjustment summary (年末調整サマリー)",
        "tags": [
          "Year-end Adjustment"
        ]
      }
    },
    "/year-end-adjustment/withholding-slip/by-employee/{employee_id}": {
      "get": {
        "description": "The same 源泉徴収票 data as `/withholding-slip/{name}`, addressed by `employees.id` (BL-968).\n\nPay slips linked to the employee match on `employee_id`; unlinked slips fall back to the employee's registered name.\nPrefer this over the name-keyed route: a payee name is neither stable nor unique.\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "employees.id of the payee",
            "in": "path",
            "name": "employee_id",
            "required": true,
            "schema": {
              "format": "uuid",
              "type": "string"
            }
          },
          {
            "description": "Fiscal year for withholding slip",
            "in": "query",
            "name": "fiscal_year",
            "required": true,
            "schema": {
              "example": 2025,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/WithholdingSlipResponse"
                }
              }
            },
            "description": "Withholding slip data generated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "message": {
                      "example": "従業員が見つかりません",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Employee not found, or no pay slips for the fiscal year"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Withholding tax slip data by employee id (源泉徴収票データ・従業員ID指定)",
        "tags": [
          "Year-end Adjustment"
        ]
      }
    },
    "/year-end-adjustment/withholding-slip/{name}": {
      "get": {
        "description": "Generate official withholding tax slip data for a specific employee.\n\n## Withholding Tax Slip Generation (源泉徴収票データ生成)\nOfficial tax document generation with:\n- **Legal Compliance**: Full compliance with Japanese tax law requirements\n- **Standardized Format**: Standard format for official withholding tax slips\n- **Comprehensive Data**: All required data elements for tax reporting\n- **Verification Support**: Data verification and validation\n- **Document Preparation**: Prepare data for official document generation\n\n## Slip Information\n- **Employee Information**: Name and identification details\n- **Income Details**: Gross income and salary income deduction\n- **Deduction Breakdown**: Detailed breakdown of all deduction categories\n- **Tax Calculations**: Calculated tax, withheld tax, and final tax amounts\n- **Credits Applied**: Housing loan and other tax credits\n- **Net Tax Amount**: Final tax amount after all adjustments\n\n## Legal Requirements\n- **Tax Law Compliance**: Full compliance with Japanese Income Tax Law\n- **Required Elements**: All legally required data elements included\n- **Calculation Accuracy**: Precise calculations following official methods\n- **Document Standards**: Adherence to official document format standards\n- **Audit Trail**: Complete audit trail for tax authority verification\n\n## Use Cases\n- **Official Documentation**: Generate official withholding tax slips for employees\n- **Tax Authority Submission**: Prepare data for tax authority submissions\n- **Employee Records**: Maintain official employee tax records\n- **Audit Preparation**: Prepare documentation for tax audits\n- **Legal Compliance**: Ensure compliance with tax reporting requirements\n\n## Authentication\nRequires valid Bearer token in Authorization header.",
        "parameters": [
          {
            "description": "Employee name (URL encoded)",
            "example": "田中太郎",
            "in": "path",
            "name": "name",
            "required": true,
            "schema": {
              "type": "string"
            }
          },
          {
            "description": "Fiscal year for withholding slip",
            "in": "query",
            "name": "fiscal_year",
            "required": true,
            "schema": {
              "example": 2024,
              "type": "integer"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/WithholdingSlipResponse"
                }
              }
            },
            "description": "Withholding slip data generated successfully"
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "content": {
              "application/json": {
                "schema": {
                  "properties": {
                    "message": {
                      "example": "従業員が見つかりません",
                      "type": "string"
                    },
                    "success": {
                      "example": false,
                      "type": "boolean"
                    }
                  },
                  "type": "object"
                }
              }
            },
            "description": "Employee not found"
          },
          "500": {
            "$ref": "#/components/responses/InternalServerError"
          }
        },
        "security": [
          {
            "bearerAuth": []
          }
        ],
        "summary": "Generate withholding tax slip data (源泉徴収票データ生成) — legacy, by payee name",
        "tags": [
          "Year-end Adjustment"
        ]
      }
    }
  },
  "servers": [
    {
      "description": "API server",
      "url": "/api"
    }
  ],
  "tags": [
    {
      "description": "System health checks, liveness/readiness probes, and circuit breaker status",
      "name": "Health"
    },
    {
      "description": "JWT admin surface: status, logs, and POST /cron/{job}/trigger (blocked in production). Production invokes EventBridge GET /api/cron/{job} with x-cron-secret (internal): warm, recover-jobs, exchange-rate, depreciation, insights, insights-weekly, trial-balance, bank-sync, cleanup, integrity-check, deadline-recompute, ledger-sync, family-hiring-monitor, compliance-rule-engine, cleanup-lp-demos, lifecycle-email, reminder-notify (a dry run unless REMINDER_NOTIFY_SEND=true), official-rules-refresh, integration-pull, stripe-payout-sync, drive-inbox-scan. reconcile-storage is not on EventBridge.",
      "name": "Cron Jobs"
    },
    {
      "description": "Version management and changelog generation from git history",
      "name": "Changelog"
    },
    {
      "description": "Background job queue management and monitoring",
      "name": "Queue Management"
    },
    {
      "description": "Composite homepage endpoint (ホームページ) — fetches all data needed by the homepage in a single request",
      "name": "Home"
    },
    {
      "description": "Composite shell endpoint (レイアウト) — the app chrome (company, accounts, reminders, holidays, ...) in one request",
      "name": "Layout"
    },
    {
      "description": "Composite endpoint for the /tax-journal page (仕訳帳) — every panel of the page in one request",
      "name": "Tax Journal"
    },
    {
      "description": "User authentication and authorization",
      "name": "Authentication"
    },
    {
      "description": "Japanese accounting configuration and tax compliance management",
      "name": "User Accounting Config"
    },
    {
      "description": "User preferences and profile configuration management",
      "name": "User Profile"
    },
    {
      "description": "User Activity Tracking API\n\n## Overview\nComprehensive user activity tracking for analytics, audit, and \"resume where you left off\" features.\n\n### 🔄 Case Conversion Middleware\nThis API uses automatic case conversion middleware:\n- **Request**: Send `camelCase` (e.g., `actionType`, `actionLabel`) - middleware converts to snake_case internally\n- **Response**: Receive `camelCase` - middleware converts from database snake_case automatically\n\n**Example Request:**\n```json\n{\n  \"actionType\": \"document_delete\",\n  \"actionLabel\": \"書類を削除\",\n  \"entityType\": \"document\"\n}\n```\n\n### 🎯 Key Features\n- **Batch Recording**: Record up to 100 activities in a single request\n- **Session Tracking**: Group activities by frontend session ID\n- **Device Metadata**: Capture browser, OS, device type, IP address\n- **Error Tracking**: Dedicated tracking for errors and API failures\n- **Advanced Search**: Filter by date range, action types, sessions, entities\n- **Configurable Retention**: Default 10,000 activities per user (90-day retention)\n\n### 📊 Rate Limits\n| Endpoint | Limit | Window |\n|----------|-------|--------|\n| POST /batch | 60 | 15 min |\n| POST / (single) | 600 | 15 min |\n| POST /search | 100 | 15 min |\n| GET endpoints | Standard | 15 min |\n\n### 🔒 Security\n- All endpoints require authentication\n- Users can only access their own activity data\n- RLS policies enforce data isolation\n- IP addresses captured for audit purposes",
      "name": "User Activity"
    },
    {
      "description": "Comprehensive notification system with real-time delivery, push notifications, and interaction tracking.\n\n### 🔄 Case Conversion Middleware\nThis API uses automatic case conversion middleware:\n- **Request**: Send `camelCase` (e.g., `readMethod`, `clickAction`) - middleware converts to snake_case internally\n- **Response**: Receive `camelCase` - middleware converts from database snake_case automatically\n\n**Example Request:**\n```json\n{\n  \"readMethod\": \"web\",\n  \"clickAction\": \"view_document\"\n}\n```",
      "name": "Notifications"
    },
    {
      "description": "Gamification System API\n\n## Overview\nEncourages user engagement by rewarding actions that align with the app's mission:\n**「経理から解放されて、本当の仕事をしよう」** (Free yourself from accounting, do the work that matters)\n\n### 🎮 Features\n- **30 User Levels** organized in 6 tiers (Beginner → Master)\n- **50+ Achievements** across 8 categories with tiered progression (Bronze → Platinum)\n- **Goals System** with daily, weekly, and feature-based goals\n- **XP Rewards** with daily limits and streak multipliers\n- **Login Streaks** for consistency tracking\n- **Time Saved Tracking** - mission-aligned metric\n\n### 🔄 Case Conversion Middleware\n- **Request**: Send `camelCase` (e.g., `eventType`, `achievementId`)\n- **Response**: Receive `camelCase` - middleware converts from snake_case\n\n### 📊 Rate Limits\n| Endpoint | Limit | Window |\n|----------|-------|--------|\n| POST /xp | 100 | 15 min |\n| POST /xp/batch | 30 | 15 min |\n| POST /login | 10 | 15 min |\n| Other endpoints | Standard | 15 min |\n\n### 🏆 Achievement Tiers\n| Tier | XP Reward |\n|------|-----------|\n| Bronze | 25 XP |\n| Silver | 50 XP |\n| Gold | 100 XP |\n| Platinum | 200 XP |\n\n### 🔥 Streak Multipliers\n| Days | Multiplier |\n|------|------------|\n| 7+ | 1.1x |\n| 30+ | 1.25x |\n| 90+ | 1.5x |\n| 365+ | 2.0x |",
      "name": "Gamification"
    },
    {
      "description": "Referral program API\n\n## Overview\nEach user gets a permanent 8-char referral code. New users that sign up via\n`?ref=CODE` and complete company onboarding trigger paired rewards:\n\n| Side     | XP   | Gems | Other                                   |\n|----------|------|------|-----------------------------------------|\n| Referrer | +500 | +50  | +1 GB storage grant (30 days)           |\n| Referee  | +200 | +20  | Permanent \"招待で参加\" badge            |\n\n### Anti-fraud\n- Self-referral blocked at the DB layer (CHECK constraint)\n- One redemption per referee, ever (UNIQUE on referee_user_id)\n- Disposable email domains rejected at redeem time\n- Same-IP rapid signup (<60s gap, 24h window) flagged at fulfilment\n- 10 rewarded referrals per referrer per calendar month — hard cap",
      "name": "Referrals"
    },
    {
      "description": "Japanese company (会社) registration, management, and legal compliance operations",
      "name": "Company Management"
    },
    {
      "description": "会社コンテキスト（会社情報・契約・取引先・未解決論点の集約）と未解決論点台帳",
      "name": "Company Context"
    },
    {
      "description": "契約・支払のアドバイス（源泉徴収・租税条約・消費税・印紙税・フリーランス法・著作権）",
      "name": "Advisories"
    },
    {
      "description": "Team member / seat management (invite, accept, revoke, role change) and the account switcher list (my-accounts).",
      "name": "Team Members"
    },
    {
      "description": "Remote MCP server for Claude (custom connector). OAuth 2.1 via Supabase Auth; read-only tools. BE ADR-0022.",
      "name": "MCP Connector"
    },
    {
      "description": "Accounting configuration for frontend UI adaptation (自動転記設定)",
      "name": "Accounting Settings"
    },
    {
      "description": "Bank account settings management for users",
      "name": "Bank Account Settings"
    },
    {
      "description": "Bank provider OAuth connections, transaction sync, and webhook handling (GMOあおぞらネット銀行 etc.)",
      "name": "Bank Integration"
    },
    {
      "description": "AI-powered company establishment guidance for Japanese business formation",
      "name": "Establishment AI"
    },
    {
      "description": "Progress tracking and management for Japanese company establishment process",
      "name": "Establishment Guide"
    },
    {
      "description": "Document management and lifecycle operations",
      "name": "Documents"
    },
    {
      "description": "\nGeneric document-to-document linking operations (v4.46: Bidirectional Linking).\n\nThis API enables linking any document to any other document, supporting:\n- **Claims** (経費申請書) → Receipts/Invoices\n- **Travel Reports** (出張報告書) → Travel Receipts\n- **Salary Slips** (給与明細書) → Supporting Documents\n- **Payment Statements** (支払明細書) → Salary Slips, Expense Claims\n- **Any document type** → Any other document type\n\n**v4.46 Bidirectional Linking:**\nWhen linking documents, BOTH documents are updated:\n- Source document gets forward link (e.g., `salarySlip` field)\n- Target document gets backlink (e.g., `paymentStatement` field)\n\n**Link Field Mapping:**\n| Source Type | Target Type | Source Field | Target Backlink |\n|-------------|-------------|--------------|-----------------|\n| payment | salary_slip | salarySlip | paymentStatement |\n| payment | claims | expenseClaims[] | paymentStatement |\n| travel | claims | expenseClaims[] | travelReport |\n| claims | travel | travelReport | expenseClaims[] |\n\n**Relationship Types:**\n- `receipt_attachment`: Receipt attached to document\n- `invoice_attachment`: Invoice attached to document  \n- `supporting_document`: General supporting document\n- `related_document`: Related/reference document\n- `source_document`: Original source document\n- `generated_from`: Generated from another document\n- `payment_to_salary`: 支払明細書 → 給与明細書\n- `salary_to_payment`: 給与明細書 → 支払明細書\n- `payment_to_expense`: 支払明細書 → 経費申請書\n- `expense_to_payment`: 経費申請書 → 支払明細書\n- `travel_to_expense`: 出張報告書 → 経費申請書\n- `expense_to_travel`: 経費申請書 → 出張報告書\n\n**Database Tables:** Queries BOTH `document_relationships` AND `expense_claim_receipts` for backwards compatibility. Also updates `documents.content.linkedDocuments` JSONB for bidirectional navigation.\n  ",
      "name": "Document Linking"
    },
    {
      "description": "User-defined custom document types\n\nCreate reusable templates beyond the 16 built-in AI document types.\nUse `POST /document-templates/extract` to infer a field skeleton from a sample file or description.\n\nDocuments created from a template use `documentType: custom` and `customTemplateId`.",
      "name": "Document Templates"
    },
    {
      "description": "Hierarchical folder management and organization",
      "name": "Folders"
    },
    {
      "description": "File upload, storage management, and organization with Supabase integration",
      "name": "File Upload"
    },
    {
      "description": "File upload grouping and document linkage (ファイルグループ管理)",
      "name": "FileGroup"
    },
    {
      "description": "Bulk file upload with AI processing and real-time progress tracking",
      "name": "Bulk Upload"
    },
    {
      "description": "Export accounting data to various formats and Japanese accounting software",
      "name": "Data Export"
    },
    {
      "description": "Japanese Electronic Book Preservation Law compliance with document management, timestamps, and audit trails",
      "name": "Electronic Book Preservation"
    },
    {
      "description": "Japanese Corporate Seal (Inkan/Hanko) Management\n\n## Overview\nManage the three standard types of Japanese corporate seals used in business documents.\n\n### 🔐 Security Features\n- **Private Storage**: Files stored in private Supabase bucket (not public)\n- **Signed URLs**: Access via time-limited signed URLs (1-hour expiry)\n- **SHA-256 Hash**: File integrity verification via cryptographic hash\n- **Full Audit Trail**: All changes logged in version_control table\n- **Soft Delete**: Files preserved for compliance/recovery\n- **RLS Policies**: Row-level security for data isolation\n\n### Seal Types\n| Type | Japanese | English | Usage |\n|------|----------|---------|-------|\n| **Jitsuin** | 実印（代表取締役印） | Corporate Registered Seal | Official contracts, registered at Legal Affairs Bureau |\n| **Ginkoin** | 銀行印 | Bank Seal | Banking operations, checks, financial transactions |\n| **Kakuin** | 角印 | Square Seal | Receipts, invoices, quotations, less formal documents |\n\n### Compliance (電子帳簿保存法)\n- IP address and user agent logged for all operations\n- Complete change history available via `/history` endpoint\n- Useful for investigating lost physical inkan cases\n\n## Features\n- Upload and replace inkan images per type\n- Retrieve inkans for document template integration\n- Support for JPEG, PNG, GIF, WebP, SVG formats\n- Maximum file size: 2MB per image\n- Automatic replacement when uploading new inkan of same type\n- Full audit history for compliance",
      "name": "Inkan"
    },
    {
      "description": "User Signature Management API\n\n## Overview\nManage user signatures for document signing - supports handwritten, digital, and initials.\n\n### 🔐 Security Features\n- **Private Storage**: Files stored in private Supabase bucket (not public)\n- **Signed URLs**: Access via time-limited signed URLs (1-hour expiry)\n- **SHA-256 Hash**: File integrity verification via cryptographic hash\n- **Full Audit Trail**: All changes logged in version_control table\n- **Soft Delete**: Files preserved for compliance/recovery\n- **RLS Policies**: Row-level security for data isolation\n\n### Signature Types\n| Type | Japanese | English | Usage |\n|------|----------|---------|-------|\n| **handwritten** | 手書きサイン | Handwritten Signature | Scanned or drawn signature image |\n| **digital** | 電子署名 | Digital Signature | Electronic signature for documents |\n| **initials** | イニシャル | Initials | Abbreviated signature using initials |\n\n### Features\n- Upload multiple signatures per type\n- Set default signature per type\n- Retrieve signatures for document templates\n- Support for JPEG, PNG, GIF, WebP, SVG formats\n- Maximum file size: 1MB per image\n- Full audit history for compliance",
      "name": "Signature"
    },
    {
      "description": "Client management and company data scraping",
      "name": "Client"
    },
    {
      "description": "AI usage tracking, analytics, and cost monitoring for client-side operations",
      "name": "Client Usage Tracking"
    },
    {
      "description": "Unified AI service for text generation, image analysis, and PDF document processing across multiple providers",
      "name": "AI Service"
    },
    {
      "description": "AI-powered business support with tax audit analysis and purchase recommendations",
      "name": "AI Business Support"
    },
    {
      "description": "AI provider and model configuration management",
      "name": "AI Configuration"
    },
    {
      "description": "Jev (OpenRouter decision model) answers narrow AI decisions — 勘定科目, 税区分 — with the existing LLM path as fallback. The platform key is limited to JEV_PLATFORM_ALLOWED_USER_IDS and metered in AI credits; other users use their own OpenRouter key (BE ADR-0013).",
      "name": "AI Decisions"
    },
    {
      "description": "Pull sources (tsumagoi C1 batches, yen-yen C2 reimbursables, Stripe payouts) booked as DRAFT journal entries that the owner approves per batch. Admin only. Tokens are write-only and stored encrypted (BE ADR-0021).",
      "name": "Integrations"
    },
    {
      "description": "Two-way sync of the deadline calendar with ONE secondary Google calendar 「一人社長 期限」 that SBC creates (scope calendar.app.created — SBC never sees the owner’s other calendars). All-day, transparent events with no attendees; tokens are stored encrypted and never returned (BE ADR-0024).",
      "name": "Google Calendar"
    },
    {
      "description": "Evidence inbox: SBC reads ONE Drive folder the owner names, extracts each new receipt, matches it to a bank row (exact yen, ±7 days) or marks it 立替, and proposes a `YYYYMMDD_勘定科目_取引先_金額円` name and an archive folder. Nothing changes in Drive until the owner approves. Scope `drive` (restricted); tokens are stored encrypted and never returned (BE ADR-0028).",
      "name": "Google Drive"
    },
    {
      "description": "Optional reminder channel: the day-before and on-the-day reminders also go to the owner’s LINE. The owner adds SBC’s official account and sends a one-time code from 通知設定; no LINE Login, no profile data is read. Dark until LINE_CHANNEL_ACCESS_TOKEN / LINE_CHANNEL_SECRET are set (BE ADR-0025).",
      "name": "LINE"
    },
    {
      "description": "AI model catalog and provider information for model selection and validation",
      "name": "AI Models"
    },
    {
      "description": "Live AI model listings fetched directly from OpenAI, Anthropic, and Vertex AI (Google Gemini) APIs",
      "name": "Provider Models"
    },
    {
      "description": "User AI preferences for personalized journal generation and categorization",
      "name": "AI Preferences"
    },
    {
      "description": "AI-powered reconciliation with transaction categorization, document matching, and automation",
      "name": "AI Reconciliation"
    },
    {
      "description": "AI-powered transaction analysis and suggestions",
      "name": "AI Analysis"
    },
    {
      "description": "AI Advisor Chat API - Conversational AI for Japanese Solo Entrepreneurs\n\n## Overview\nConversational AI chat service with context injection, memory management, and legal citation capabilities.\n\n### 🎯 Features\n- **Conversational Chat** - Multi-turn conversations with history\n- **Quick Questions** - One-off questions without saving history\n- **Context Injection** - Company info, fiscal year, business objectives\n- **Memory Management** - 4,000 token budget with summarization\n- **Legal Citations** - Japanese tax law references in answers\n- **Suggested Questions** - Context-aware question suggestions\n\n### 🤖 AI Capabilities\n- Japanese tax law expertise\n- Accounting advice for solo entrepreneurs\n- Plain language explanations\n- Actionable recommendations\n- Legal basis citations (法律根拠)\n\n### 📝 Response Structure\n| Field | Description |\n|-------|-------------|\n| answer | Main response text |\n| confidence | high/medium/low |\n| legalBasis | Referenced laws and sections |\n| actionItems | Recommended actions |\n| warnings | Important caveats |\n| followUpQuestions | Suggested next questions |\n\n### 🔄 Conversation Memory\n- **Token Budget**: 4,000 tokens per conversation\n- **Summarization**: Auto-summarizes when reaching limit\n- **Context**: Includes last 5 exchanges",
      "name": "Advisor"
    },
    {
      "description": "AI-powered text generation, image analysis, and embeddings",
      "name": "OpenAI"
    },
    {
      "description": "Bank statement transaction management, AI-powered import, and financial categorization for Japanese banking",
      "name": "Bank Statements"
    },
    {
      "description": "Comprehensive bank reconciliation system with intelligent matching, Japanese accounting compliance, and automated workflows",
      "name": "Bank Reconciliation"
    },
    {
      "description": "Document-transaction linking with 17 linkage types, audit trail, and P2034 deadlock retry. v4.17: Enriched document details. v4.18: Transaction retry logic.",
      "name": "Reconciliation Linkage"
    },
    {
      "description": "Smart document search for matching bank transactions",
      "name": "Document Search"
    },
    {
      "description": "Expense management and financial tracking",
      "name": "Expenses"
    },
    {
      "description": "\n経費精算ウィザード - AI-powered expense assistant for Japanese solo entrepreneurs (一人社長).\n\n**v5.5 - PDF Text Extraction (Default) vs AI Vision OCR (Optional):**\n- **Server-side pdfjs**: Now DEFAULT for PDF analysis - faster, more accurate for Japanese text\n- **AI Vision OCR**: Now OPTIONAL - enable in AI Settings (設定 > AI設定 > use_vision_ocr)\n- **Benefits**: No garbled Japanese text (mojibake), faster processing, lower API costs\n- **When to enable Vision OCR**: Scanned/image-based PDFs without text layers\n- **Image files**: Require Vision OCR to be enabled (cannot extract text from images)\n\n**v5.4 - Robust Session Management (Dev-Friendly):**\n- **Enhanced 429 response**: Returns `existing_sessions` array when at limit\n- **Auto-cleanup option**: Set `force_cleanup: true` to auto-cancel stale drafts (>24h)\n- **Frontend-friendly errors**: Actionable suggestions in error response\n- **Session resumption**: Easy to resume existing draft sessions\n\n**v5.3 - Auto Journal Entry Creation:**\n- **Atomic journal creation**: Set `auto_create_journal: true` when creating documents\n- **Supported types**: `claims` (立替経費申請書), `salary_slip` (給与明細書)\n- **Japanese GAAP compliance**: 発生主義 (accrual accounting) - expenses recognized when confirmed\n- **No manual sync needed**: Eliminates the separate journal sync step\n\n**v4.56 - Educational AI for Solo Entrepreneurs:**\n- **Plain Japanese explanations**: Why each category, tax rules, document retention\n- **家事按分 detection**: Auto-detects home office, vehicle, mobile splits with guidance\n- **Tax-saving tips**: 青色申告メリット, 中小企業特例, 会議費活用\n- **Audit preparation**: What to record, how long to keep, common mistakes\n\n**v4.55 - Tax/Audit Intelligence:**\n- Company context (定款) validation\n- Tax deductibility analysis\n- Alternative category suggestions with reasoning\n\n**v4.54 - Performance:**\n- 3x faster with parallel AI processing\n- Server-side PDF text extraction (v5.5 default) + optional Vision OCR fallback\n- Auto-retry with exponential backoff\n- 300+ vendor/keyword categorization rules\n- Business relevance validation against 定款\n- Anomaly detection (duplicates, high amounts)\n- Automatic document chain creation (Travel → Claims → Salary → Payment)\n- Bank transaction linking\n- **Real-time SSE progress updates** with query parameter auth (v4.53)\n\n**Workflow:**\n1. Create session with trip type and document configuration\n2. (Optional) Connect SSE for real-time updates\n3. Upload receipt files (PDF, images)\n4. Trigger AI analysis → receive progress via SSE\n5. Review and correct extracted data\n6. Preview generated documents\n7. Create documents with `auto_create_journal: true` for automatic journal entries\n\n**Session Persistence & Restoration:**\n- Sessions are persisted in `expense_wizard_sessions` table\n- Items are persisted in `expense_wizard_items` table\n- Use `GET /sessions?status=draft` to list resumable sessions\n- Use `GET /sessions/{id}` to restore session state\n- SSE supports cross-device synchronization\n  ",
      "name": "Expense Wizard"
    },
    {
      "description": "\nExpense claim document linking operations.\n\nLink receipts and invoices to expense claims for the reimbursement workflow.\n\n**Frontend Contract:**\n- Send request bodies in `camelCase` (auto-converted to snake_case)\n- Receive response bodies in `camelCase` (auto-converted from snake_case)\n- Use `linkedInvoices`, `linkedReceipts`, `linkedDocumentCount` in responses\n  ",
      "name": "Expense Claims"
    },
    {
      "description": "\n## 経費カテゴリルール API (v4.52)\n\nIntelligent expense categorization system using rule-based vendor/keyword matching with machine learning from user corrections.\n\n### Features\n- **300+ System Rules**: Pre-configured Japanese vendor and keyword matching rules\n- **User Customization**: Create personal override rules with higher priority\n- **Learning System**: Records user corrections to improve suggestions over time\n- **Batch Processing**: Categorize multiple items in a single request\n- **Amount Adjustments**: Automatic confidence adjustments based on amount thresholds\n\n### Categorization Priority\n1. User's custom rules (priority 70-90)\n2. System vendor rules (priority 50-90)\n3. System keyword rules (priority 40-70)\n4. User's historical patterns\n5. Default (その他)\n\n### Available Categories (0-26)\n| ID | Japanese | English |\n|----|----------|---------|\n| 0 | 接待交際費 | Entertainment |\n| 1 | 会議費 | Meeting Expenses |\n| 2 | 事務用品費 | Office Supplies |\n| 3 | 旅費交通費 | Travel & Transport |\n| 4 | 広告宣伝費 | Advertising |\n| 5 | 水道光熱費 | Utilities |\n| 6 | 賃借料 | Rent |\n| 7 | 通信費 | Communication |\n| 8 | 外注費 | Outsourcing |\n| 9 | 消耗品費 | Supplies |\n| 10 | 修繕費 | Repairs |\n| 11 | 保険料 | Insurance |\n| 12 | 研修費 | Training |\n| 13 | 支払手数料 | Legal/Professional Fees |\n| 14 | 備品費 | Equipment |\n| 15 | 燃料費 | Fuel |\n| 16 | 開業費 | Pre-establishment |\n| 17 | 設立費 | Establishment |\n| 18 | その他 | Others |\n| 19 | 接待飲食費 | Entertainment Dining |\n| 20 | 福利厚生費 | Welfare Benefits |\n| 21 | 新聞図書費 | Books & Publications |\n| 22 | 諸会費 | Membership Dues |\n| 23 | 寄付金 | Donations |\n| 24 | 採用費 | Recruitment |\n| 25 | 車両費 | Vehicle Expenses |\n| 26 | リース料 | Lease Payments |\n",
      "name": "Expense Category Rules"
    },
    {
      "description": "Japanese expense reimbursement workflow management and document linking",
      "name": "Reimbursement Workflow"
    },
    {
      "description": "合算支払 — one itemized 支払明細書 over N unsettled claims (no salary slip, no bank row)",
      "name": "Settlement Pack"
    },
    {
      "description": "通知書センター — e-Gov / e-Tax / eLTAX notices imported from ZIP",
      "name": "Notice Documents"
    },
    {
      "description": "Credit card registration and management for tracking statements and payments",
      "name": "Credit Cards"
    },
    {
      "description": "Chart of Accounts management and retrieval",
      "name": "Accounts"
    },
    {
      "description": "Composite accounting dock summary for frontend optimization.\n\n## Overview\nSingle consolidated endpoint that aggregates data from multiple accounting services:\n- **Journal Entries**: Count, status breakdown, source type breakdown, balance check\n- **General Ledger**: Account count, debit/credit totals, balance verification\n- **Trial Balance**: Active account count, period totals, discrepancy\n- **Source Statistics**: Expense document, bank transaction, and manual entry counts\n- **Workflow**: Pending draft count\n\n## Performance\nReplaces 5+ separate API calls with a single request. All underlying queries\nexecute in parallel using `Promise.all()` for optimal response time (~200ms).\n\n## Caching\nResults are cached per-user for 60 seconds. Cache is invalidated when journal\nentries are created, updated, or deleted.",
      "name": "Accounting Dock"
    },
    {
      "description": "Rule-based accounting logic for transaction classification, transfer detection, and journal entry generation.\n\n## Overview\nNon-AI, deterministic accounting operations using configurable transaction rules:\n- **Transaction Classification**: Match bank transactions to debit/credit accounts by keyword\n- **Transfer Detection**: Identify inter-account transfers between bank accounts\n- **Journal Entry Generation**: Generate journal entries from bank transactions\n\n## Rule Engine\nUses predefined `TRANSACTION_RULES` that match transaction descriptions to accounting categories.\nEach rule maps keywords to debit/credit account codes, tax rates, and remark templates.",
      "name": "Accounting Logic"
    },
    {
      "description": "Japanese double-entry bookkeeping and accounting journal management",
      "name": "Journal Entries"
    },
    {
      "description": "Journal Templates (仕訳辞書) for automated accounting entry creation",
      "name": "Journal Templates"
    },
    {
      "description": "Remark Dictionary (摘要辞書) for accounting description management and auto-suggestion",
      "name": "Remark Dictionary"
    },
    {
      "description": "Comprehensive Japanese financial reporting system with trial balance, P&L, balance sheet, KPI analytics, and business insights",
      "name": "Financial Reports"
    },
    {
      "description": "全エンジン統合の指摘事項一覧 (申告前・整合性・月次・顧問)",
      "name": "Findings"
    },
    {
      "description": "申告済みの申告書（受信データ）と、その時点の帳簿を固定し、現在の帳簿との差異を仕訳単位で示す",
      "name": "FiledReturns"
    },
    {
      "description": "Japanese trial balance (試算表) generation with period comparison and financial analysis",
      "name": "Trial Balance"
    },
    {
      "description": "Japanese general ledger management with double-entry bookkeeping and running balance tracking",
      "name": "General Ledger"
    },
    {
      "description": "Compliance deadline management — calendar, complete, dismiss, recompute",
      "name": "Deadlines"
    },
    {
      "description": "会社のできごと（本店移転・代表者の変更など）の記録と、それで始まる届出の期限",
      "name": "Company events"
    },
    {
      "description": "銀行の出金から見つかった納付の候補（記録するのは、オーナーが確認したときだけ）",
      "name": "Tax payment matches"
    },
    {
      "description": "忘れていませんか — 立替の登録漏れ・未精算・未払い、いつもの定例作業の遅れ（判定は決定的、AIなし）",
      "name": "Habit reminders"
    },
    {
      "description": "決算確定・申告書の前に解決が必要な確認事項（税理士の回答・理由付きの確認・監査記録つきの続行）",
      "name": "Year close"
    },
    {
      "description": "お金の流れ — 証憑から経費・精算書・支払明細書・振込・仕訳までのつながりと、支払い済みかどうか",
      "name": "Money trail"
    },
    {
      "description": "すべての記録をまとめて検索（書類・ファイル・経費・銀行取引・仕訳・取引先）",
      "name": "Search"
    },
    {
      "description": "申告・届出の控え（e-Tax 受信通知・eLTAX 受付通知）の取り込みと、提出済みにする期限の提案",
      "name": "Filing receipts"
    },
    {
      "description": "納税キャッシュフロー予測 — 12-month rolling tax obligation timeline",
      "name": "Tax Forecast"
    },
    {
      "description": "登記・定款 health monitor — director term, みなし解散, 決算公告",
      "name": "Corporate Registry"
    },
    {
      "description": "帳簿連携 — freee OAuth connect/disconnect/sync",
      "name": "Ledger Integration"
    },
    {
      "description": "Japanese fixed asset management with depreciation calculation and tax compliance",
      "name": "Fixed Assets"
    },
    {
      "description": "棚卸資産台帳 (Inventory Ledger)\n\nJ-GAAP inventory items, 商品有高帳 movements, year-end valuation, and disposal.\nv5.71 adds `inventory_asset` vs `tracked_supply` classification and bulk ingest from expenses.\n\nFrontend: `/inventory-ledger` · Feature: `inventory/`",
      "name": "Inventory"
    },
    {
      "description": "Sales invoice management and processing",
      "name": "Sales Invoices"
    },
    {
      "description": "Sales document workflow chain status for dock UX.\n\n## Overview\nReturns the full sales document workflow chain (見積書→発注書→納品書→請求書) for a given document,\nincluding linked documents, current stage, sales invoice details, and available workflow actions.\n\n## Use Cases\n- Sales dock initial load (independent of parent page context)\n- Workflow status refresh without full page reload\n- Available action detection for workflow advancement\n\n## Performance\n- **Target**: <200ms response time\n- **Caching**: 60-second per-user memory cache\n- **Queries**: 3-4 database queries (document + relationships + chain expansion + optional sales invoice)",
      "name": "Sales Workflow"
    },
    {
      "description": "Japanese Qualified Invoice System with multi-tax rate support and legal compliance",
      "name": "Qualified Invoice"
    },
    {
      "description": "Immutable audit trail tables for 電子帳簿保存法 (Electronic Bookkeeping Act) compliance",
      "name": "Audit Logs"
    },
    {
      "description": "Owner-side auditor/accountant view — overview, audit pack ZIP, evidence bundle ZIP, and share-link management. Public token routes under /public/auditor-view.",
      "name": "Auditor View"
    },
    {
      "description": "Owner-authored 5W1H context for outside professionals (税理士・監査人 等) — who they are and why they are engaged. Narrative memo only; never serialized into a tax filing.",
      "name": "Professional Engagements"
    },
    {
      "description": "Regulatory compliance and government API integration",
      "name": "Compliance"
    },
    {
      "description": "Japanese tax compliance management with fiscal period controls and withholding tax calculations",
      "name": "Tax Compliance"
    },
    {
      "description": "弥生・freee・マネーフォワード・会計王・汎用の仕訳データ（CSV / TSV / .xlsx / 貼り付け）と期首残高ファイルの取り込み",
      "name": "AccountingImport"
    },
    {
      "description": "Composite endpoint for the tax-compliance page — fetches journal summary by account and bank statements in parallel to eliminate waterfall requests (v4.74)",
      "name": "Tax Compliance Init"
    },
    {
      "description": "Japanese consumption tax return calculation with multiple methods and optimization recommendations",
      "name": "Consumption Tax"
    },
    {
      "description": "確定申告セッション persistence, submitted returns, 申告情報 parties, print bundle",
      "name": "Tax Filing"
    },
    {
      "description": "修正申告 lifecycle — status, materiality, start/complete/cancel, 監査メモ",
      "name": "Filing Amendment"
    },
    {
      "description": "Imported filing files — list/import/compare/CRUD/duplicate",
      "name": "Filing Workspace"
    },
    {
      "description": "Japanese year-end tax adjustment processing with comprehensive deduction management and tax calculation",
      "name": "Year-end Adjustment"
    },
    {
      "description": "Data integrity checking and validation system for financial data quality assurance",
      "name": "Integrity Checks"
    },
    {
      "description": "多拠点（分割法人）support — office registry, 均等割 (per-capita levy) simulation and apportionment, 納付記録 (tax payment records), and filing-progress tracking.",
      "name": "Multi-Office"
    },
    {
      "description": "Japanese payroll management system with comprehensive pay slip tracking, YTD calculations, and accounting integration",
      "name": "Pay Slips"
    },
    {
      "description": "\n## 従業員管理 (Employee Management System)\n\nComplete employee management for Japanese business entities:\n\n### Supported Entity Types\n- **株式会社 (KK)** - Joint Stock Company with directors, employees, auditors\n- **合同会社 (GK)** - Limited Liability Company with managing members\n- **個人事業主** - Sole Proprietorship with family employees (専従者)\n\n### Position Types (for 法定調書 threshold calculation)\n\n| Position | Japanese | Compensation | 法定調書 Threshold |\n|----------|----------|--------------|-------------------|\n| representative_director | 代表取締役 | 役員報酬 | ¥1,500,000 |\n| director | 取締役 | 役員報酬 | ¥1,500,000 |\n| auditor | 監査役 | 役員報酬 | ¥1,500,000 |\n| representative_member | 代表社員 (GK) | 役員報酬 | ¥1,500,000 |\n| managing_member | 業務執行社員 (GK) | 役員報酬 | ¥1,500,000 |\n| employee_director | 使用人兼務役員 | Mixed | ¥1,500,000 |\n| regular_employee | 正社員 | 給与 | ¥5,000,000 |\n| contract_employee | 契約社員 | 給与 | ¥5,000,000 |\n| part_time | パート・アルバイト | 給与 | ¥5,000,000 |\n| family_employee | 専従者 | 専従者給与 | ¥5,000,000 |\n| sole_proprietor | 事業主 | N/A | N/A |\n",
      "name": "Employees"
    },
    {
      "description": "役員社宅 (Executive Company Housing)\n\nProperty setup → 課税明細書 / 賃貸借契約書 OCR with human verification gates →\nimmutable 賃貸料相当額 calculation snapshots → document generation → monthly charges →\ncompany rent payments with bank reconciliation.\n\nFrontend: `/shataku-setup` · Feature: `shataku-setup/`",
      "name": "Shataku"
    },
    {
      "description": "親族雇用 (Family Hiring) Module\n\nIntake wizard → Classification engine (CORP_EMPLOYEE / CORP_OFFICER / みなし役員 / 専従者) →\nWalls evaluation (130万 / 106万 / 103万 / 住民税非課税) → Salary optimizer (scenarios A–E) →\nReasonableness guard (過大給与) → Document generation (雇用契約書・就業規則等) →\nWork log (勤務証憑) → Daily wall monitor.\n\nFrontend: `/family-hiring` · Feature: `family-hiring/`",
      "name": "FamilyHiring"
    },
    {
      "description": "Reference data holder for business lookup values, enums, and chart of accounts",
      "name": "Reference Data"
    },
    {
      "description": "Multi-currency exchange rate management with external API integration and caching",
      "name": "Exchange Rates"
    },
    {
      "description": "Japanese business reminder system for tax deadlines, compliance requirements, and custom scheduling",
      "name": "Reminders"
    },
    {
      "description": "役員報酬 — schedule and the 改定 advisor (when a change stays 定期同額給与)",
      "name": "Officer Compensation"
    },
    {
      "description": "Proactive Insights API - AI Advisor System\n\n## Overview\nProactive insights engine that generates and delivers timely, relevant notifications to help Japanese solo entrepreneurs with tax savings, compliance, and deadlines.\n\n### 🎯 Features\n- **Contextual Insights** - Screen-specific insights based on current context\n- **Insight Types** - Tax saving, compliance warnings, deadlines, optimization\n- **Priority Levels** - Urgent, High, Medium, Low\n- **30-day Dismissal** - Dismissed insights resurface after 30 days\n- **Combined Insights** - Similar insights grouped for cleaner display\n\n### 📊 Insight Types\n| Type | Description | Icon |\n|------|-------------|------|\n| tax_saving | Tax savings opportunities | 💰 |\n| compliance_warning | Compliance issues | ⚠️ |\n| deadline | Upcoming deadlines | 📅 |\n| optimization | Optimization suggestions | 💡 |\n| missing_document | Missing documents | 📋 |\n| cash_flow_alert | Cash flow concerns | 💳 |\n| audit_risk | Audit risk indicators | ⚡ |\n| achievement | Positive milestones | 🎉 |\n\n### 🔄 Insight Lifecycle\n1. **New** - Just generated, unread\n2. **Viewed** - User has seen the insight\n3. **Acted** - User took action on the insight\n4. **Dismissed** - User dismissed (resurfaces after 30 days)\n\n### 📱 Screen-Specific Insights\nDifferent screens show different insight types:\n- **Dashboard** - tax_saving, deadline, compliance_warning\n- **Expense Wizard** - tax_saving, optimization, deadline\n- **Bank Statement** - compliance_warning, optimization",
      "name": "Insights"
    },
    {
      "description": "Mapbox integration and map utility endpoints for real estate visualization",
      "name": "Mapbox"
    },
    {
      "description": "High-performance map data streaming with batch processing, caching, and optimization",
      "name": "Map Streaming"
    },
    {
      "description": "Knowledge Base API - Japanese Tax & Accounting Rules\n\n## Overview\nSearchable knowledge base containing Japanese tax laws, accounting rules, and business guidance for solo entrepreneurs.\n\n### 📚 Categories\n| Category | Description |\n|----------|-------------|\n| expense | 経費 - Business expenses |\n| income | 収入 - Income types |\n| deduction | 控除 - Tax deductions |\n| tax_filing | 確定申告 - Tax filing |\n| consumption_tax | 消費税 - Consumption tax |\n| withholding_tax | 源泉徴収 - Withholding tax |\n| bookkeeping | 帳簿記帳 - Bookkeeping |\n| document_retention | 書類保存 - Document retention |\n| invoice_system | インボイス制度 - Invoice system |\n| depreciation | 減価償却 - Depreciation |\n| home_office | 自宅兼事務所 - Home office |\n| compliance | コンプライアンス - Compliance |\n\n### 🔍 Features\n- **Search**: Full-text search across all articles\n- **Categories**: Browse by topic\n- **Screen-specific**: Get relevant articles for current UI screen\n- **Learn More**: Get detailed content for \"詳しく\" buttons\n\n### 📝 Article Structure\nEach article includes:\n- Title (Japanese and English)\n- Summary\n- Full content (Markdown)\n- Legal basis citations\n- Related topics\n- Practical examples\n- Warnings/caveats",
      "name": "Knowledge Base"
    },
    {
      "description": "Curated official tax/legal corpus (e-Gov statutes, NTA Tax Answer, e-Tax). eLTax is link-only.",
      "name": "Official Rules"
    },
    {
      "description": "Message Library API - Advisor Message Templates\n\n## Overview\nAPI for exploring and previewing all advisor messages used in the application. Useful for FE development, testing, and potential future customization.\n\n### 📁 Categories\n| Category | Description |\n|----------|-------------|\n| expense | Expense wizard messages |\n| bank | Bank statement messages |\n| compliance | Compliance status messages |\n| tax | Tax deadline and filing messages |\n| document | Document management messages |\n| completion | Task completion celebrations |\n| encouragement | Motivational messages |\n| error | Error response templates |\n| loading | Loading state messages |\n\n### 🔧 Use Cases\n- **FE Development**: Preview messages during UI development\n- **Testing**: Verify message formatting and content\n- **Localization**: Review all user-facing text\n- **Customization**: (Future) Allow message customization\n\n### 📝 Message Structure\nEach message returns:\n- `message`: Text with emoji for visual display\n- `plain`: Plain text without emoji for accessibility",
      "name": "Message Library"
    },
    {
      "description": "Admin log management, real-time streaming, and migration status",
      "name": "Admin Logs"
    },
    {
      "description": "Database schema documentation and metadata",
      "name": "Database Documentation"
    },
    {
      "description": "Demo data lifecycle management, reset, validation, and statistics",
      "name": "Demo Data Management"
    },
    {
      "description": "Unauthenticated, rate-limited landing page demo tools",
      "name": "Public Demo"
    },
    {
      "description": "First-party product analytics. Unauthenticated (optional bearer), rate-limited, insert-only. Client events are batched (max 20) and stitched to an account through the anonymous id.",
      "name": "Product Events"
    },
    {
      "description": "One-click stop for the onboarding mail series. Token-authenticated (HMAC minted per user), no login.",
      "name": "Public Lifecycle"
    },
    {
      "description": "Unauthenticated document share viewer. Successful GET increments access_count — not a pure read.",
      "name": "Public Document Shares"
    },
    {
      "description": "Public same-origin proxy for browser Sentry envelopes (ad-blocker bypass). Allowlisted host + project only. See docs/sentry-tunnel.md.",
      "name": "Sentry Tunnel"
    },
    {
      "description": "Public same-origin proxy for browser Mushi ingest (ad-blocker bypass). Allowlisted host + project + /v1/ path only. See docs/mushi-tunnel.md.",
      "name": "Mushi Tunnel"
    },
    {
      "description": "Demo processing run history and execution tracking",
      "name": "Demo Processing"
    },
    {
      "description": "Test script execution history and result tracking",
      "name": "Test Scripts"
    },
    {
      "description": "Financial simulation session management with auto-sync and transaction tracking",
      "name": "Simulation Sessions"
    },
    {
      "description": "Pre-defined financial statement templates for simulation",
      "name": "Simulation Templates"
    }
  ],
  "x-tagGroups": [
    {
      "name": "🏥 System",
      "tags": [
        "Health",
        "Cron Jobs",
        "Changelog",
        "Queue Management"
      ]
    },
    {
      "name": "🏠 Composite Endpoints",
      "tags": [
        "Home",
        "Layout"
      ]
    },
    {
      "name": "🔐 Authentication & User",
      "tags": [
        "Authentication",
        "User Accounting Config",
        "User Profile",
        "User Activity",
        "Notifications",
        "Gamification"
      ]
    },
    {
      "name": "🏢 Company & Settings",
      "tags": [
        "Company Management",
        "Team Members",
        "MCP Connector",
        "Accounting Settings",
        "Bank Account Settings",
        "Establishment AI",
        "Establishment Guide"
      ]
    },
    {
      "name": "📄 Documents & Files",
      "tags": [
        "Documents",
        "Document Linking",
        "Document Templates",
        "Folders",
        "File Upload",
        "FileGroup",
        "Bulk Upload",
        "Data Export",
        "Electronic Book Preservation",
        "Inkan",
        "Signature"
      ]
    },
    {
      "name": "👥 Clients",
      "tags": [
        "Client",
        "Client Usage Tracking"
      ]
    },
    {
      "name": "🤖 AI Features",
      "tags": [
        "AI Service",
        "AI Business Support",
        "AI Configuration",
        "AI Models",
        "Provider Models",
        "AI Preferences",
        "AI Reconciliation",
        "AI Analysis",
        "Advisor",
        "OpenAI"
      ]
    },
    {
      "name": "🏦 Bank & Reconciliation",
      "tags": [
        "Bank Statements",
        "Bank Reconciliation",
        "Reconciliation Links",
        "Document Search"
      ]
    },
    {
      "name": "💳 Expenses & Reimbursements",
      "tags": [
        "Expenses",
        "Expense Wizard",
        "Expense Claims",
        "Expense Category Rules",
        "Reimbursement Workflow",
        "Credit Cards"
      ]
    },
    {
      "name": "📊 Accounting",
      "tags": [
        "Accounts",
        "Accounting Logic",
        "Journal Entries",
        "Journal Templates",
        "Remark Dictionary"
      ]
    },
    {
      "name": "📈 Financial Reports",
      "tags": [
        "Financial Reports",
        "Trial Balance",
        "General Ledger"
      ]
    },
    {
      "name": "🏠 Assets & Invoices",
      "tags": [
        "Fixed Assets",
        "Inventory",
        "Sales Invoices",
        "Qualified Invoice"
      ]
    },
    {
      "name": "📋 Tax & Compliance",
      "tags": [
        "Audit Logs",
        "Compliance",
        "Tax Compliance",
        "AccountingImport",
        "Tax Compliance Init",
        "Consumption Tax",
        "Tax Filing",
        "Filing Amendment",
        "Filing Workspace",
        "Year-end Adjustment",
        "Integrity Checks",
        "Multi-Office"
      ]
    },
    {
      "name": "👔 Payroll & HR",
      "tags": [
        "Pay Slips",
        "Employees",
        "Shataku"
      ]
    },
    {
      "name": "⚙️ Reference & Settings",
      "tags": [
        "Reference Data",
        "Exchange Rates",
        "Reminders",
        "Insights"
      ]
    },
    {
      "name": "🗺️ Maps",
      "tags": [
        "Mapbox",
        "Map Streaming"
      ]
    },
    {
      "name": "📚 Knowledge & Support",
      "tags": [
        "Knowledge Base",
        "Official Rules",
        "Message Library"
      ]
    },
    {
      "name": "🛠️ Developer & Admin",
      "tags": [
        "Admin Logs",
        "Database Documentation",
        "Demo Data Management",
        "Public Demo",
        "Sentry Tunnel",
        "Mushi Tunnel",
        "Demo Processing",
        "Test Scripts"
      ]
    },
    {
      "name": "🎮 Simulation",
      "tags": [
        "Simulation Sessions",
        "Simulation Templates"
      ]
    }
  ]
}
