{"openapi":"3.0.3","info":{"title":"Securi Force API","version":"1.0.0","description":"Securi service platform API for managing emergency calls, brigades, and dispatch operations","contact":{"name":"Securi Force Development Team","email":"temirlan0597@gmail.com","url":"https://securiforce.kg"},"license":{"name":"MIT","url":"https://opensource.org/licenses/MIT"}},"servers":[{"url":"https://api.securiforce.kg","description":"Production server"},{"url":"http://localhost:3000","description":"Development server"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"JWT","description":"JWT token for authentication"}},"schemas":{"ApiResponse":{"type":"object","properties":{"success":{"type":"boolean","description":"Indicates if the request was successful"},"message":{"type":"string","description":"Response message"},"data":{"type":"object","description":"Response data"},"error":{"type":"object","description":"Error details if request failed"}},"required":["success"]},"PaginatedResponse":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"array","items":{"type":"object"}},"pagination":{"type":"object","properties":{"page":{"type":"integer","minimum":1},"limit":{"type":"integer","minimum":1,"maximum":100},"total":{"type":"integer","minimum":0},"totalPages":{"type":"integer","minimum":0}}}}},"User":{"type":"object","properties":{"id":{"type":"string","format":"uuid","description":"Unique user identifier"},"email":{"type":"string","format":"email","description":"User email address"},"first_name":{"type":"string","description":"User first name"},"last_name":{"type":"string","description":"User last name"},"phone":{"type":"string","pattern":"^\\+?[1-9]\\d{1,14}$","description":"User phone number"},"role":{"type":"string","enum":["client","dispatcher","brigade_member","admin"],"description":"User role in the system"},"status":{"type":"string","enum":["active","inactive","suspended"],"description":"User account status"},"avatar_url":{"type":"string","format":"uri","description":"URL to user's profile picture","nullable":true},"createdAt":{"type":"string","format":"date-time"},"updatedAt":{"type":"string","format":"date-time"}},"required":["id","email","first_name","last_name","role","status"]},"Call":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"clientId":{"type":"string","format":"uuid"},"brigadeId":{"type":"string","format":"uuid","nullable":true},"type":{"type":"string","enum":["emergency","security","maintenance","consultation"]},"priority":{"type":"string","enum":["low","medium","high","critical"]},"status":{"type":"string","enum":["pending","assigned","in_progress","completed","cancelled"]},"title":{"type":"string","description":"Brief description of the call"},"description":{"type":"string","description":"Detailed description of the issue"},"address":{"type":"string","description":"Location address"},"coordinates":{"type":"object","properties":{"latitude":{"type":"number","format":"double","minimum":-90,"maximum":90},"longitude":{"type":"number","format":"double","minimum":-180,"maximum":180}}},"estimatedDuration":{"type":"integer","description":"Estimated duration in minutes"},"actualDuration":{"type":"integer","description":"Actual duration in minutes"},"totalCost":{"type":"number","format":"decimal","description":"Total cost of the service"},"createdAt":{"type":"string","format":"date-time"},"assignedAt":{"type":"string","format":"date-time","nullable":true},"startedAt":{"type":"string","format":"date-time","nullable":true},"completedAt":{"type":"string","format":"date-time","nullable":true}},"required":["id","clientId","type","priority","status","title","address"]},"Brigade":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"name":{"type":"string","description":"Brigade name"},"description":{"type":"string","description":"Brigade description"},"status":{"type":"string","enum":["active","inactive","on_call","busy"]},"currentLocation":{"type":"object","properties":{"latitude":{"type":"number","format":"double"},"longitude":{"type":"number","format":"double"},"address":{"type":"string"}}},"specializations":{"type":"array","items":{"type":"string"},"description":"Brigade specializations"},"createdAt":{"type":"string","format":"date-time"}},"required":["id","name","status"]},"LoginRequest":{"type":"object","properties":{"email":{"type":"string","description":"Account identifier: an email address or a phone number. The field is named `email` for compatibility with released mobile builds; the server resolves which one it is from the value.","example":"user@example.com"},"password":{"type":"string","minLength":6}},"required":["email","password"]},"LoginResponse":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"object","properties":{"token":{"type":"string","description":"JWT access token"},"refreshToken":{"type":"string","description":"Refresh token"},"user":{"$ref":"#/components/schemas/User"},"expiresIn":{"type":"integer","description":"Token expiration time in seconds"}}}}},"ValidationError":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string","example":"Validation failed"},"details":{"type":"array","items":{"type":"object","properties":{"field":{"type":"string"},"message":{"type":"string"}}}}}}}},"UnauthorizedError":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string","example":"Unauthorized access"}}}}},"NotFoundError":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string","example":"Resource not found"}}}}},"ForbiddenError":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string","example":"Forbidden access"}}}}},"InternalServerError":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string","example":"Internal server error"}}}}},"AppPlatformVersions":{"type":"object","properties":{"ios":{"$ref":"#/components/schemas/PlatformVersion"},"android":{"$ref":"#/components/schemas/PlatformVersion"}}},"PlatformVersion":{"type":"object","properties":{"latestVersion":{"type":"string","example":"1.0.2"},"minimumVersion":{"type":"string","example":"1.0.0"},"storeUrl":{"type":"string"},"releaseNotes":{"type":"string"}}},"AppVersionRecord":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"appKey":{"type":"string","enum":["client","brigada","orc"]},"platform":{"type":"string","enum":["ios","android"]},"latestVersion":{"type":"string"},"minimumVersion":{"type":"string"},"storeUrl":{"type":"string"},"releaseNotes":{"type":"string"},"updatedAt":{"type":"string","format":"date-time"}}},"UpdateAppVersionRequest":{"type":"object","properties":{"latestVersion":{"type":"string","pattern":"^\\d+\\.\\d+\\.\\d+$","example":"1.1.0"},"minimumVersion":{"type":"string","pattern":"^\\d+\\.\\d+\\.\\d+$","example":"1.0.0"},"storeUrl":{"type":"string"},"releaseNotes":{"type":"string"}}},"AuditLog":{"type":"object","properties":{"id":{"type":"string","format":"uuid","description":"Unique identifier for the audit log entry"},"userId":{"type":"string","format":"uuid","description":"ID of the user who performed the action"},"action":{"type":"string","description":"Action that was performed","example":"user_created"},"resource":{"type":"string","description":"Resource that was affected","example":"users"},"resourceId":{"type":"string","format":"uuid","description":"ID of the specific resource that was affected"},"details":{"type":"object","additionalProperties":true,"description":"Additional details about the action"},"ipAddress":{"type":"string","format":"ipv4","description":"IP address from which the action was performed","example":"192.168.1.100"},"userAgent":{"type":"string","description":"User agent string from the request"},"timestamp":{"type":"string","format":"date-time","description":"When the action was performed"}},"required":["id","action","resource","timestamp"]},"AuditLogWithUser":{"allOf":[{"$ref":"#/components/schemas/AuditLog"},{"type":"object","properties":{"user":{"oneOf":[{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"firstName":{"type":"string"},"lastName":{"type":"string"},"email":{"type":"string","format":"email"},"role":{"type":"string","enum":["client","dispatcher","admin","brigade_member"]}}},{"type":"null"}],"description":"User information (null if user was deleted or system action)"}}}]},"PaginatedAuditLogs":{"type":"object","properties":{"logs":{"type":"array","items":{"$ref":"#/components/schemas/AuditLogWithUser"}},"pagination":{"$ref":"#/components/schemas/PaginationInfo"},"summary":{"type":"object","properties":{"totalLogs":{"type":"integer","description":"Total number of audit logs"},"uniqueUsers":{"type":"integer","description":"Number of unique users in the logs"},"topActions":{"type":"array","items":{"type":"object","properties":{"action":{"type":"string"},"count":{"type":"integer"}}},"description":"Most frequent actions"},"topResources":{"type":"array","items":{"type":"object","properties":{"resource":{"type":"string"},"count":{"type":"integer"}}},"description":"Most frequently accessed resources"}}}},"required":["logs","pagination"]},"Car":{"type":"object","required":["licensePlate","model"],"properties":{"id":{"type":"string","format":"uuid"},"licensePlate":{"type":"string","maxLength":20},"model":{"type":"string","maxLength":100},"year":{"type":"integer","minimum":1900},"color":{"type":"string","maxLength":50},"photoUrl":{"type":"string","format":"uri"},"status":{"type":"string","enum":["active","maintenance","inactive"]},"gpsDeviceId":{"type":"string","maxLength":100},"brigadeId":{"type":"string","format":"uuid"},"createdAt":{"type":"string","format":"date-time"},"updatedAt":{"type":"string","format":"date-time"}}},"CreateCarRequest":{"type":"object","required":["licensePlate","model"],"properties":{"licensePlate":{"type":"string","minLength":1,"maxLength":20,"description":"Vehicle license plate number"},"model":{"type":"string","minLength":1,"maxLength":100,"description":"Vehicle model name"},"year":{"type":"integer","minimum":1900,"description":"Vehicle manufacture year"},"color":{"type":"string","maxLength":50,"description":"Vehicle color"},"photoUrl":{"type":"string","format":"uri","description":"URL to vehicle photo"},"status":{"type":"string","enum":["active","maintenance","inactive"],"default":"active","description":"Vehicle operational status"},"gpsDeviceId":{"type":"string","maxLength":100,"description":"GPS tracking device identifier"},"brigadeId":{"type":"string","format":"uuid","description":"ID of the brigade this car is assigned to"}}},"UpdateCarRequest":{"type":"object","properties":{"licensePlate":{"type":"string","minLength":1,"maxLength":20},"model":{"type":"string","minLength":1,"maxLength":100},"year":{"type":"integer","minimum":1900},"color":{"type":"string","maxLength":50},"photoUrl":{"type":"string","format":"uri"},"status":{"type":"string","enum":["active","maintenance","inactive"]},"gpsDeviceId":{"type":"string","maxLength":100},"brigadeId":{"type":"string","format":"uuid"}}},"ChatMessage":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"callId":{"type":"string","format":"uuid"},"senderId":{"type":"string","format":"uuid"},"message":{"type":"string"},"messageType":{"type":"string","enum":["text","image","location","file"]},"fileUrl":{"type":"string","format":"uri","nullable":true},"isRead":{"type":"boolean"},"createdAt":{"type":"string","format":"date-time"},"sender":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"first_name":{"type":"string"},"last_name":{"type":"string"},"role":{"type":"string","enum":["client","dispatcher","brigade_member","admin"]}}}},"example":{"id":"123e4567-e89b-12d3-a456-426614174000","callId":"456e7890-e89b-12d3-a456-426614174001","senderId":"789e0123-e89b-12d3-a456-426614174002","message":"We are on our way to your location","messageType":"text","fileUrl":null,"isRead":false,"createdAt":"2024-01-15T10:30:00Z","sender":{"id":"789e0123-e89b-12d3-a456-426614174002","first_name":"John","last_name":"Smith","role":"brigade_member"}}},"ClientAddress":{"type":"object","properties":{"id":{"type":"string","format":"uuid","description":"Unique identifier for the address"},"userId":{"type":"string","format":"uuid","description":"ID of the user who owns this address"},"name":{"type":"string","description":"Display name for the address","example":"Home"},"address":{"type":"string","description":"Full address string","example":"123 Main St, Bishkek, Kyrgyzstan"},"coordinates":{"type":"object","properties":{"lat":{"type":"number","format":"float","minimum":-90,"maximum":90,"description":"Latitude coordinate"},"lng":{"type":"number","format":"float","minimum":-180,"maximum":180,"description":"Longitude coordinate"}}},"isDefault":{"type":"boolean","description":"Whether this is the user's default address"},"createdAt":{"type":"string","format":"date-time","description":"When the address was created"},"updatedAt":{"type":"string","format":"date-time","description":"When the address was last updated"}},"required":["id","userId","name","address","coordinates","isDefault","createdAt","updatedAt"]},"CreateClientAddressRequest":{"type":"object","properties":{"userId":{"type":"string","format":"uuid","description":"Target client user ID. Admin/dispatcher only — creates the address for another user."},"name":{"type":"string","minLength":2,"maxLength":100,"description":"Display name for the address","example":"Home"},"address":{"type":"string","minLength":5,"maxLength":500,"description":"Full address string. Coordinates are always resolved server-side via Google Geocoding — do not send coordinates in the request.","example":"123 Main St, Bishkek, Kyrgyzstan"},"isDefault":{"type":"boolean","description":"Whether this should be the default address","default":false}},"required":["name","address"]},"UpdateClientAddressRequest":{"type":"object","properties":{"name":{"type":"string","minLength":2,"maxLength":100,"description":"Display name for the address"},"address":{"type":"string","minLength":5,"maxLength":500,"description":"Full address string. When changed, coordinates are re-geocoded automatically server-side."},"isDefault":{"type":"boolean","description":"Whether this should be the default address"}}},"NearbySearchRequest":{"type":"object","properties":{"lat":{"type":"number","format":"float","minimum":-90,"maximum":90,"description":"Latitude coordinate for search center"},"lng":{"type":"number","format":"float","minimum":-180,"maximum":180,"description":"Longitude coordinate for search center"},"radius":{"type":"number","minimum":100,"maximum":10000,"default":1000,"description":"Search radius in meters"},"limit":{"type":"number","minimum":1,"maximum":50,"default":10,"description":"Maximum number of results to return"}},"required":["lat","lng"]},"PaginatedClientAddresses":{"type":"object","properties":{"addresses":{"type":"array","items":{"$ref":"#/components/schemas/ClientAddress"}},"pagination":{"$ref":"#/components/schemas/PaginationInfo"}},"required":["addresses","pagination"]},"ConnectedObject":{"type":"object","properties":{"id":{"type":"string","format":"uuid","description":"Unique identifier for the connected object"},"clientId":{"type":"string","format":"uuid","description":"ID of the client who owns this object"},"name":{"type":"string","description":"Display name for the object","example":"Front Door Camera"},"type":{"type":"string","enum":["camera","sensor","alarm","lock","other"],"description":"Type of connected object"},"status":{"type":"string","enum":["active","inactive","alarm","maintenance"],"description":"Current status of the object"},"deviceId":{"type":"string","description":"Unique device identifier","example":"CAM-001-ABC123"},"location":{"type":"string","description":"Physical location description","example":"Front entrance"},"coordinates":{"type":"object","properties":{"lat":{"type":"number","format":"float","minimum":-90,"maximum":90,"description":"Latitude coordinate"},"lng":{"type":"number","format":"float","minimum":-180,"maximum":180,"description":"Longitude coordinate"}}},"lastSeen":{"type":"string","format":"date-time","description":"When the device was last seen online"},"batteryLevel":{"type":"integer","minimum":0,"maximum":100,"description":"Battery level percentage"},"signalStrength":{"type":"integer","minimum":0,"maximum":100,"description":"Signal strength percentage"},"metadata":{"type":"object","additionalProperties":true,"description":"Additional device-specific metadata"},"createdAt":{"type":"string","format":"date-time","description":"When the object was created"},"updatedAt":{"type":"string","format":"date-time","description":"When the object was last updated"}},"required":["id","clientId","name","type","status","deviceId","createdAt","updatedAt"]},"ConnectedObjectWithClient":{"allOf":[{"$ref":"#/components/schemas/ConnectedObject"},{"type":"object","properties":{"client":{"oneOf":[{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"firstName":{"type":"string"},"lastName":{"type":"string"},"email":{"type":"string","format":"email"},"phone":{"type":"string"}}},{"type":"null"}],"description":"Client information (null if client was deleted)"}}}]},"CreateConnectedObjectRequest":{"type":"object","properties":{"clientId":{"type":"string","format":"uuid","description":"ID of the client who owns this object"},"name":{"type":"string","minLength":2,"maxLength":100,"description":"Display name for the object","example":"Front Door Camera"},"type":{"type":"string","enum":["camera","sensor","alarm","lock","other"],"description":"Type of connected object"},"deviceId":{"type":"string","minLength":3,"maxLength":50,"description":"Unique device identifier","example":"CAM-001-ABC123"},"location":{"type":"string","maxLength":200,"description":"Physical location description","example":"Front entrance"},"coordinates":{"type":"object","properties":{"lat":{"type":"number","format":"float","minimum":-90,"maximum":90,"description":"Latitude coordinate"},"lng":{"type":"number","format":"float","minimum":-180,"maximum":180,"description":"Longitude coordinate"}},"required":["lat","lng"]},"metadata":{"type":"object","additionalProperties":true,"description":"Additional device-specific metadata"}},"required":["clientId","name","type","deviceId"]},"UpdateConnectedObjectRequest":{"type":"object","properties":{"name":{"type":"string","minLength":2,"maxLength":100,"description":"Display name for the object"},"type":{"type":"string","enum":["camera","sensor","alarm","lock","other"],"description":"Type of connected object"},"status":{"type":"string","enum":["active","inactive","alarm","maintenance"],"description":"Current status of the object"},"location":{"type":"string","maxLength":200,"description":"Physical location description"},"coordinates":{"type":"object","properties":{"lat":{"type":"number","format":"float","minimum":-90,"maximum":90,"description":"Latitude coordinate"},"lng":{"type":"number","format":"float","minimum":-180,"maximum":180,"description":"Longitude coordinate"}},"required":["lat","lng"]},"batteryLevel":{"type":"integer","minimum":0,"maximum":100,"description":"Battery level percentage"},"signalStrength":{"type":"integer","minimum":0,"maximum":100,"description":"Signal strength percentage"},"metadata":{"type":"object","additionalProperties":true,"description":"Additional device-specific metadata"}}},"DeviceStatusUpdateRequest":{"type":"object","properties":{"status":{"type":"string","enum":["active","inactive","alarm","maintenance"],"description":"Current status of the device"},"batteryLevel":{"type":"integer","minimum":0,"maximum":100,"description":"Battery level percentage"},"signalStrength":{"type":"integer","minimum":0,"maximum":100,"description":"Signal strength percentage"},"metadata":{"type":"object","additionalProperties":true,"description":"Additional device-specific metadata"}},"required":["status"]},"PaginatedConnectedObjects":{"type":"object","properties":{"objects":{"type":"array","items":{"$ref":"#/components/schemas/ConnectedObjectWithClient"}},"pagination":{"$ref":"#/components/schemas/PaginationInfo"},"summary":{"type":"object","properties":{"totalObjects":{"type":"integer","description":"Total number of objects"},"activeObjects":{"type":"integer","description":"Number of active objects"},"alarmObjects":{"type":"integer","description":"Number of objects in alarm state"},"inactiveObjects":{"type":"integer","description":"Number of inactive objects"},"maintenanceObjects":{"type":"integer","description":"Number of objects in maintenance"}}}},"required":["objects","pagination"]},"LegalEntity":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"companyName":{"type":"string","maxLength":200},"legalName":{"type":"string","maxLength":200},"taxId":{"type":"string","maxLength":50},"registrationNumber":{"type":"string","maxLength":100},"email":{"type":"string","format":"email"},"phone":{"type":"string","maxLength":20},"website":{"type":"string","format":"uri"},"legalAddress":{"type":"string"},"billingAddress":{"type":"string"},"industry":{"type":"string","maxLength":100},"employeeCount":{"type":"integer","minimum":1},"description":{"type":"string"},"status":{"type":"string","enum":["active","suspended","inactive"]},"verified":{"type":"boolean"},"createdAt":{"type":"string","format":"date-time"},"updatedAt":{"type":"string","format":"date-time"}}},"CorporateLocation":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"legalEntityId":{"type":"string","format":"uuid"},"name":{"type":"string","maxLength":200},"address":{"type":"string"},"coordinates":{"type":"object","properties":{"lat":{"type":"number","minimum":-90,"maximum":90},"lng":{"type":"number","minimum":-180,"maximum":180}}},"locationType":{"type":"string","enum":["office","warehouse","factory","retail","residential","other"]},"servicesEnabled":{"type":"array","items":{"type":"string"}},"contactPerson":{"type":"string","maxLength":200},"contactPhone":{"type":"string","maxLength":20},"isActive":{"type":"boolean"},"createdAt":{"type":"string","format":"date-time"},"updatedAt":{"type":"string","format":"date-time"}}},"CorporateEmployee":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"legalEntityId":{"type":"string","format":"uuid"},"userId":{"type":"string","format":"uuid"},"employeeId":{"type":"string","maxLength":50},"department":{"type":"string","maxLength":100},"position":{"type":"string","maxLength":100},"canMakeCalls":{"type":"boolean"},"canAccessLocations":{"type":"array","items":{"type":"string","format":"uuid"}},"accessLevel":{"type":"string","enum":["employee","manager","admin"]},"employmentStartDate":{"type":"string","format":"date"},"user":{"type":"object","properties":{"firstName":{"type":"string"},"lastName":{"type":"string"},"email":{"type":"string"},"phone":{"type":"string"}}}}},"CreateLegalEntityRequest":{"type":"object","required":["companyName","legalName","taxId","email","legalAddress"],"properties":{"companyName":{"type":"string","maxLength":200,"description":"Public company name"},"legalName":{"type":"string","maxLength":200,"description":"Official legal name"},"taxId":{"type":"string","maxLength":50,"description":"Tax identification number"},"registrationNumber":{"type":"string","maxLength":100,"description":"Company registration number"},"email":{"type":"string","format":"email","description":"Company contact email"},"phone":{"type":"string","maxLength":20,"description":"Company phone number"},"website":{"type":"string","format":"uri","description":"Company website URL"},"legalAddress":{"type":"string","description":"Official legal address"},"billingAddress":{"type":"string","description":"Billing address (if different from legal)"},"industry":{"type":"string","maxLength":100,"description":"Industry sector"},"employeeCount":{"type":"integer","minimum":1,"description":"Total number of employees"},"description":{"type":"string","description":"Company description"}}},"AddCorporateLocationRequest":{"type":"object","required":["legalEntityId","name","address","locationType"],"properties":{"legalEntityId":{"type":"string","format":"uuid","description":"ID of the legal entity this location belongs to"},"name":{"type":"string","maxLength":200,"description":"Location name"},"address":{"type":"string","description":"Location address"},"coordinates":{"type":"object","properties":{"lat":{"type":"number","minimum":-90,"maximum":90},"lng":{"type":"number","minimum":-180,"maximum":180}},"description":"Geographic coordinates"},"locationType":{"type":"string","enum":["office","warehouse","factory","retail","residential","other"],"description":"Type of location"},"servicesEnabled":{"type":"array","items":{"type":"string"},"description":"List of enabled service identifiers"},"contactPerson":{"type":"string","maxLength":200,"description":"Contact person name at location"},"contactPhone":{"type":"string","maxLength":20,"description":"Contact phone number at location"},"isActive":{"type":"boolean","default":true,"description":"Whether the location is active"}}},"UpdateCorporateLocationRequest":{"type":"object","required":["legalEntityId"],"properties":{"legalEntityId":{"type":"string","format":"uuid","description":"ID of the legal entity this location belongs to"},"name":{"type":"string","maxLength":200},"address":{"type":"string"},"coordinates":{"type":"object","properties":{"lat":{"type":"number","minimum":-90,"maximum":90},"lng":{"type":"number","minimum":-180,"maximum":180}}},"locationType":{"type":"string","enum":["office","warehouse","factory","retail","residential","other"]},"servicesEnabled":{"type":"array","items":{"type":"string"}},"contactPerson":{"type":"string","maxLength":200},"contactPhone":{"type":"string","maxLength":20},"isActive":{"type":"boolean","description":"Whether the location is active"}}},"AddCorporateEmployeeRequest":{"type":"object","required":["legalEntityId","userId"],"properties":{"legalEntityId":{"type":"string","format":"uuid","description":"ID of the legal entity"},"userId":{"type":"string","format":"uuid","description":"ID of the user to add as employee"},"employeeId":{"type":"string","maxLength":50,"description":"Internal employee identifier"},"department":{"type":"string","maxLength":100,"description":"Employee department"},"position":{"type":"string","maxLength":100,"description":"Employee position/title"},"canMakeCalls":{"type":"boolean","default":true,"description":"Whether the employee can make emergency calls"},"canAccessLocations":{"type":"array","items":{"type":"string","format":"uuid"},"description":"List of location IDs the employee can access"},"accessLevel":{"type":"string","enum":["employee","manager","admin"],"default":"employee","description":"Employee access level within the corporate account"},"employmentStartDate":{"type":"string","format":"date","description":"Employment start date"}}},"UpdateCorporateEmployeeRequest":{"type":"object","properties":{"department":{"type":"string","maxLength":100,"description":"Employee department"},"position":{"type":"string","maxLength":100,"description":"Employee position/title"},"canMakeCalls":{"type":"boolean","description":"Whether the employee can make emergency calls"},"canAccessLocations":{"type":"array","items":{"type":"string","format":"uuid"},"description":"List of location IDs the employee can access"},"accessLevel":{"type":"string","enum":["employee","manager","admin"],"description":"Employee access level within the corporate account"}}},"CreateCorporateEmergencyCallRequest":{"type":"object","required":["locationId","description"],"properties":{"locationId":{"type":"string","format":"uuid","description":"Corporate location ID where emergency occurred"},"description":{"type":"string","maxLength":500,"description":"Description of the emergency"},"eventType":{"type":"string","maxLength":50,"description":"Type of event (e.g., fire, intrusion, medical)"},"severity":{"type":"string","enum":["low","medium","high","critical"],"default":"high","description":"Severity level of the emergency"}}},"DeviceToken":{"type":"object","properties":{"id":{"type":"string","format":"uuid","description":"Device token ID"},"userId":{"type":"string","format":"uuid","description":"User ID"},"token":{"type":"string","description":"FCM/APNs device token"},"platform":{"type":"string","enum":["ios","android","web"],"description":"Device platform"},"isActive":{"type":"boolean","description":"Whether token is active"},"createdAt":{"type":"string","format":"date-time","description":"Creation timestamp"},"updatedAt":{"type":"string","format":"date-time","description":"Last update timestamp"}},"example":{"id":"550e8400-e29b-41d4-a716-446655440000","userId":"660e8400-e29b-41d4-a716-446655440001","token":"fMI-EXAMPLE-TOKEN-dQw4w9WgXcQ:APA91bH...","platform":"ios","isActive":true,"createdAt":"2024-01-15T10:30:00Z","updatedAt":"2024-01-15T10:30:00Z"}},"RegisterDeviceTokenRequest":{"type":"object","required":["token","platform"],"properties":{"token":{"type":"string","minLength":10,"maxLength":500,"description":"FCM/APNs device token"},"platform":{"type":"string","enum":["ios","android","web"],"description":"Device platform"},"appType":{"type":"string","enum":["client","brigade"],"description":"Which mobile app registered this token (client or brigade). Used to route notifications to the correct app."}},"example":{"token":"fMI-EXAMPLE-TOKEN-dQw4w9WgXcQ:APA91bH...","platform":"ios","appType":"brigade"}},"EnhancedUserProfile":{"type":"object","properties":{"id":{"type":"string","format":"uuid","description":"User ID"},"first_name":{"type":"string","description":"First name"},"last_name":{"type":"string","description":"Last name"},"email":{"type":"string","format":"email","description":"Email address"},"phone":{"type":"string","nullable":true,"description":"Phone number"},"role":{"type":"string","enum":["admin","dispatcher","brigade_member","client"],"description":"User role"},"familySubscription":{"type":"object","nullable":true,"description":"Family subscription context (present if user is part of a family plan)","properties":{"id":{"type":"string","format":"uuid","description":"Subscription ID"},"type":{"type":"string","enum":["primary","member"],"description":"Whether user is the primary subscriber or a family member"},"relationship":{"type":"string","nullable":true,"description":"Relationship to primary subscriber (for members)"},"isMinor":{"type":"boolean","nullable":true,"description":"Whether the family member is a minor"},"primaryUserName":{"type":"string","nullable":true,"description":"Name of the primary subscriber (for members)"},"familyMembers":{"type":"array","nullable":true,"description":"List of family members (for primary subscribers)","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"userId":{"type":"string","format":"uuid"},"name":{"type":"string"},"relationship":{"type":"string"},"isMinor":{"type":"boolean"},"phone":{"type":"string"}}}}}},"corporateAccess":{"type":"object","nullable":true,"description":"Corporate access context (present if user is a corporate employee)","properties":{"id":{"type":"string","format":"uuid","description":"Corporate employee record ID"},"companyName":{"type":"string","description":"Legal entity company name"},"employeeId":{"type":"string","nullable":true,"description":"Internal employee ID"},"department":{"type":"string","nullable":true,"description":"Department name"},"position":{"type":"string","nullable":true,"description":"Job position"},"accessLevel":{"type":"string","description":"Access level within the corporate account"},"canMakeCalls":{"type":"boolean","description":"Whether the employee can initiate emergency calls"},"accessibleLocations":{"type":"array","nullable":true,"description":"Corporate locations the employee can access","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"name":{"type":"string"},"address":{"type":"string"},"location_type":{"type":"string"}}}}}},"activeSubscription":{"type":"object","nullable":true,"description":"Active subscription details","properties":{"id":{"type":"string","format":"uuid","description":"Subscription ID"},"tariffName":{"type":"string","description":"Name of the tariff plan"},"subscriptionType":{"type":"string","description":"Subscription type"},"status":{"type":"string","description":"Subscription status"},"nextPaymentDate":{"type":"string","format":"date-time","nullable":true,"description":"Next payment due date"},"services":{"type":"array","description":"List of included services","items":{"type":"string","enum":["security","fire_alarm","video_surveillance","access_control","medical_alert"]}}}},"emergencyContacts":{"type":"array","description":"List of emergency contacts","items":{"$ref":"#/components/schemas/EmergencyContact"}},"medicalInfo":{"type":"object","nullable":true,"description":"Medical information (available for family members)","properties":{"conditions":{"type":"string","nullable":true,"description":"Medical conditions"},"allergies":{"type":"string","nullable":true,"description":"Known allergies"},"medications":{"type":"string","nullable":true,"description":"Current medications"}}},"preferences":{"type":"object","nullable":true,"description":"User preferences","properties":{"notifications":{"type":"boolean","description":"Whether notifications are enabled"},"language":{"type":"string","description":"Preferred language"},"timezone":{"type":"string","description":"Preferred timezone"}}}},"example":{"id":"550e8400-e29b-41d4-a716-446655440000","first_name":"Иван","last_name":"Иванов","email":"ivan@example.com","phone":"+996700123456","role":"client","familySubscription":null,"corporateAccess":null,"activeSubscription":{"id":"660e8400-e29b-41d4-a716-446655440001","tariffName":"Базовый","subscriptionType":"monthly","status":"active","nextPaymentDate":"2024-02-15T00:00:00Z","services":["security"]},"emergencyContacts":[],"medicalInfo":null,"preferences":{"notifications":true,"language":"en","timezone":"Asia/Bishkek"}}},"EmergencyContact":{"type":"object","properties":{"id":{"type":"string","format":"uuid","description":"Contact ID"},"name":{"type":"string","description":"Contact name"},"relationship":{"type":"string","description":"Relationship to the user"},"phone":{"type":"string","description":"Contact phone number"},"priority":{"type":"integer","minimum":1,"description":"Contact priority (1 = highest)"}},"example":{"id":"770e8400-e29b-41d4-a716-446655440002","name":"Мария Иванова","relationship":"Супруга","phone":"+996700654321","priority":1}},"UpdateProfileRequest":{"type":"object","description":"Fields to update on the user profile. All fields are optional.","properties":{"first_name":{"type":"string","maxLength":100,"description":"First name"},"last_name":{"type":"string","maxLength":100,"description":"Last name"},"phone":{"type":"string","maxLength":20,"description":"Phone number"},"preferences":{"type":"object","description":"User preferences","properties":{"notifications":{"type":"boolean"},"language":{"type":"string","maxLength":10},"timezone":{"type":"string","maxLength":50}}},"medicalInfo":{"type":"object","description":"Medical information (for family members)","properties":{"conditions":{"type":"string","maxLength":1000},"allergies":{"type":"string","maxLength":500},"medications":{"type":"string","maxLength":500}}}},"example":{"first_name":"Иван","last_name":"Петров","phone":"+996700111222","preferences":{"notifications":true,"language":"ru","timezone":"Asia/Bishkek"}}},"AddEmergencyContactRequest":{"type":"object","required":["name","relationship","phone"],"properties":{"name":{"type":"string","maxLength":200,"description":"Contact name"},"relationship":{"type":"string","maxLength":50,"description":"Relationship to the user"},"phone":{"type":"string","maxLength":20,"description":"Contact phone number"},"priority":{"type":"integer","minimum":1,"default":1,"description":"Contact priority (1 = highest)"}},"example":{"name":"Мария Иванова","relationship":"Супруга","phone":"+996700654321","priority":1}},"UserContextSummary":{"type":"object","properties":{"userType":{"type":"string","enum":["individual","family_primary","family_member","corporate_employee"],"description":"Determined user type based on subscriptions and corporate access"},"canMakeEmergencyCalls":{"type":"boolean","description":"Whether the user can initiate emergency calls"},"availableServices":{"type":"array","description":"List of services available to the user","items":{"type":"string"}},"emergencyContacts":{"type":"integer","description":"Number of emergency contacts"},"subscriptionStatus":{"type":"string","description":"Current subscription status or \"none\""},"familyMembersCount":{"type":"integer","description":"Number of family members (0 if not in a family plan)"},"corporateLocationsCount":{"type":"integer","description":"Number of accessible corporate locations (0 if not corporate)"}},"example":{"userType":"individual","canMakeEmergencyCalls":true,"availableServices":["security"],"emergencyContacts":2,"subscriptionStatus":"active","familyMembersCount":0,"corporateLocationsCount":0}},"UserDashboard":{"type":"object","properties":{"profile":{"$ref":"#/components/schemas/EnhancedUserProfile"},"recentCalls":{"type":"array","description":"Recent calls by the user (up to 10)","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"description":{"type":"string"},"status":{"type":"string"},"priority":{"type":"string"},"created_at":{"type":"string","format":"date-time"},"address":{"type":"string"}}}},"familyActivity":{"type":"array","nullable":true,"description":"Recent family activity (present if user is in a family plan)","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"description":{"type":"string"},"status":{"type":"string"},"created_at":{"type":"string","format":"date-time"},"first_name":{"type":"string"},"last_name":{"type":"string"}}}},"corporateActivity":{"type":"array","nullable":true,"description":"Recent corporate activity (present if user has corporate access)","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"description":{"type":"string"},"status":{"type":"string"},"created_at":{"type":"string","format":"date-time"},"location_name":{"type":"string"}}}},"notifications":{"type":"array","description":"Recent notifications (up to 20)","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"title":{"type":"string"},"message":{"type":"string"},"type":{"type":"string"},"is_read":{"type":"boolean"},"created_at":{"type":"string","format":"date-time"}}}},"quickActions":{"type":"array","description":"Available quick actions based on user context","items":{"type":"string","enum":["emergency_call","add_family_member","manage_family","corporate_emergency","view_locations","view_subscription","payment_history"]}}}},"FamilyMember":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"userId":{"type":"string","format":"uuid"},"relationship":{"type":"string","enum":["child","spouse","parent","sibling","guardian","other"]},"isMinor":{"type":"boolean"},"canMakeCalls":{"type":"boolean"},"requiresParentNotification":{"type":"boolean"},"emergencyContactPriority":{"type":"integer","minimum":1},"medicalConditions":{"type":"string","maxLength":1000},"allergies":{"type":"string","maxLength":500},"medications":{"type":"string","maxLength":500},"first_name":{"type":"string"},"last_name":{"type":"string"},"email":{"type":"string"},"phone":{"type":"string"}}},"FamilySubscription":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"userId":{"type":"string","format":"uuid"},"tariffId":{"type":"string","format":"uuid"},"status":{"type":"string"},"paymentMethod":{"type":"string"},"createdAt":{"type":"string","format":"date-time"}}},"CreateFamilySubscriptionRequest":{"type":"object","required":["tariffId"],"properties":{"tariffId":{"type":"string","format":"uuid","description":"ID of the tariff plan for the family subscription"},"paymentMethod":{"type":"string","description":"Payment method identifier"}}},"AddFamilyMemberRequest":{"type":"object","required":["emailOrPhone","relationship"],"properties":{"primaryUserId":{"type":"string","format":"uuid","description":"(Admin/Dispatcher only) Target user whose family subscription to manage. If omitted, uses the authenticated user's subscription."},"emailOrPhone":{"type":"string","description":"Email or phone of the user. If user not found and this is an email, a new account is auto-created with generated credentials sent to this email."},"firstName":{"type":"string","maxLength":100,"description":"First name for auto-created user (optional, user can fill profile later)"},"lastName":{"type":"string","maxLength":100,"description":"Last name for auto-created user (optional, user can fill profile later)"},"phone":{"type":"string","maxLength":20,"description":"Phone number for auto-created user (optional)"},"relationship":{"type":"string","enum":["child","spouse","parent","sibling","guardian","other"],"description":"Relationship to the primary subscriber"},"isMinor":{"type":"boolean","default":false,"description":"Whether the family member is a minor"},"canMakeCalls":{"type":"boolean","default":true,"description":"Whether the family member can make emergency calls"},"requiresParentNotification":{"type":"boolean","default":false,"description":"Whether calls from this member trigger parent notifications"},"emergencyContactPriority":{"type":"integer","minimum":1,"default":1,"description":"Priority order for emergency contact list"},"medicalConditions":{"type":"string","maxLength":1000,"description":"Known medical conditions"},"allergies":{"type":"string","maxLength":500,"description":"Known allergies"},"medications":{"type":"string","maxLength":500,"description":"Current medications"}}},"UpdateFamilyMemberRequest":{"type":"object","properties":{"relationship":{"type":"string","enum":["child","spouse","parent","sibling","guardian","other"]},"isMinor":{"type":"boolean"},"canMakeCalls":{"type":"boolean"},"requiresParentNotification":{"type":"boolean"},"emergencyContactPriority":{"type":"integer","minimum":1},"medicalConditions":{"type":"string","maxLength":1000},"allergies":{"type":"string","maxLength":500},"medications":{"type":"string","maxLength":500}}},"CreateFamilyEmergencyCallRequest":{"type":"object","required":["description"],"properties":{"description":{"type":"string","maxLength":500,"description":"Description of the emergency"},"coordinates":{"type":"object","properties":{"lat":{"type":"number","minimum":-90,"maximum":90},"lng":{"type":"number","minimum":-180,"maximum":180}},"description":"Geographic coordinates of the emergency"},"address":{"type":"string","maxLength":500,"description":"Address of the emergency"}}},"HealthCheckResponse":{"type":"object","properties":{"status":{"type":"string","description":"Server health status","example":"OK"},"timestamp":{"type":"string","format":"date-time","description":"Current server timestamp","example":"2024-01-15T10:30:00.000Z"},"environment":{"type":"string","description":"Current runtime environment","example":"development"},"version":{"type":"string","description":"Application version","example":"1.0.0"}},"required":["status","timestamp","environment","version"],"example":{"status":"OK","timestamp":"2024-01-15T10:30:00.000Z","environment":"development","version":"1.0.0"}},"Invoice":{"type":"object","properties":{"id":{"type":"string","format":"uuid","description":"Unique identifier for the invoice"},"callId":{"type":"string","format":"uuid","description":"ID of the associated call"},"clientId":{"type":"string","format":"uuid","description":"ID of the client"},"amount":{"type":"number","format":"float","minimum":0,"description":"Invoice amount","example":150.5},"status":{"type":"string","enum":["pending","paid","overdue","cancelled"],"description":"Invoice status"},"paymentMethod":{"type":"string","enum":["cash","card","bank_transfer","mobile_payment","crypto"],"description":"Payment method used"},"paymentReference":{"type":"string","description":"Payment reference or transaction ID"},"dueDate":{"type":"string","format":"date-time","description":"When the invoice is due"},"paidAt":{"type":"string","format":"date-time","description":"When the invoice was paid"},"createdAt":{"type":"string","format":"date-time","description":"When the invoice was created"},"updatedAt":{"type":"string","format":"date-time","description":"When the invoice was last updated"}},"required":["id","callId","clientId","amount","status","createdAt","updatedAt"]},"InvoiceWithDetails":{"allOf":[{"$ref":"#/components/schemas/Invoice"},{"type":"object","properties":{"call":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"title":{"type":"string"},"type":{"type":"string"},"address":{"type":"string"},"completedAt":{"type":"string","format":"date-time"}}},"client":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"firstName":{"type":"string"},"lastName":{"type":"string"},"email":{"type":"string","format":"email"},"phone":{"type":"string"}}}}}]},"CreateInvoiceRequest":{"type":"object","properties":{"callId":{"type":"string","format":"uuid","description":"ID of the completed call"},"clientId":{"type":"string","format":"uuid","description":"ID of the client"},"amount":{"type":"number","format":"float","minimum":0.01,"description":"Invoice amount","example":150.5},"dueDate":{"type":"string","format":"date-time","description":"When the invoice is due (optional, defaults to 30 days)"},"paymentMethod":{"type":"string","enum":["cash","card","bank_transfer","mobile_payment","crypto"],"description":"Expected payment method"}},"required":["callId","clientId","amount"]},"UpdateInvoiceRequest":{"type":"object","properties":{"status":{"type":"string","enum":["pending","paid","overdue","cancelled"],"description":"Invoice status"},"paymentMethod":{"type":"string","enum":["cash","card","bank_transfer","mobile_payment","crypto"],"description":"Payment method"},"paymentReference":{"type":"string","maxLength":100,"description":"Payment reference or transaction ID"},"dueDate":{"type":"string","format":"date-time","description":"When the invoice is due"}}},"PayInvoiceRequest":{"type":"object","properties":{"paymentMethod":{"type":"string","enum":["cash","card","bank_transfer","mobile_payment","crypto"],"description":"Payment method used"},"paymentReference":{"type":"string","maxLength":100,"description":"Payment reference or transaction ID"}},"required":["paymentMethod"]},"PaginatedInvoices":{"type":"object","properties":{"invoices":{"type":"array","items":{"$ref":"#/components/schemas/InvoiceWithDetails"}},"pagination":{"$ref":"#/components/schemas/PaginationInfo"},"summary":{"type":"object","properties":{"totalAmount":{"type":"number","format":"float","description":"Total amount of all invoices"},"paidAmount":{"type":"number","format":"float","description":"Total amount of paid invoices"},"pendingAmount":{"type":"number","format":"float","description":"Total amount of pending invoices"},"overdueAmount":{"type":"number","format":"float","description":"Total amount of overdue invoices"}}}},"required":["invoices","pagination"]},"InvoiceStats":{"type":"object","properties":{"totalInvoices":{"type":"integer","description":"Total number of invoices"},"totalAmount":{"type":"number","format":"float","description":"Total amount of all invoices"},"paidAmount":{"type":"number","format":"float","description":"Total amount of paid invoices"},"pendingAmount":{"type":"number","format":"float","description":"Total amount of pending invoices"},"overdueAmount":{"type":"number","format":"float","description":"Total amount of overdue invoices"},"averageAmount":{"type":"number","format":"float","description":"Average invoice amount"},"paymentMethodBreakdown":{"type":"object","additionalProperties":{"type":"integer"},"description":"Count of invoices by payment method","example":{"card":45,"cash":23,"bank_transfer":12}}},"required":["totalInvoices","totalAmount","paidAmount","pendingAmount","overdueAmount","averageAmount","paymentMethodBreakdown"]},"NotificationData":{"type":"object","required":["type","title","message"],"properties":{"id":{"type":"string","format":"uuid","description":"Notification ID"},"type":{"type":"string","enum":["call","assignment","status","message","alert","system"],"description":"Type of notification"},"title":{"type":"string","maxLength":200,"description":"Notification title"},"message":{"type":"string","maxLength":1000,"description":"Notification message content"},"data":{"type":"object","description":"Additional notification data"},"isRead":{"type":"boolean","description":"Whether notification has been read"},"sentAt":{"type":"string","format":"date-time","description":"When notification was sent"},"createdAt":{"type":"string","format":"date-time","description":"Creation timestamp"},"updatedAt":{"type":"string","format":"date-time","description":"Last update timestamp"}},"example":{"id":"550e8400-e29b-41d4-a716-446655440000","type":"call","title":"Новый вызов","message":"Поступил новый вызов от клиента","data":{"callId":"660e8400-e29b-41d4-a716-446655440001"},"isRead":false,"sentAt":"2024-01-15T10:30:00Z","createdAt":"2024-01-15T10:30:00Z","updatedAt":"2024-01-15T10:30:00Z"}},"NotificationPreferences":{"type":"object","required":["emailNotifications","pushNotifications","smsNotifications","notificationTypes"],"properties":{"emailNotifications":{"type":"boolean","description":"Enable email notifications"},"pushNotifications":{"type":"boolean","description":"Enable push notifications"},"smsNotifications":{"type":"boolean","description":"Enable SMS notifications"},"notificationTypes":{"type":"array","items":{"type":"string"},"description":"Array of enabled notification types"}},"example":{"emailNotifications":true,"pushNotifications":true,"smsNotifications":false,"notificationTypes":["call","assignment","status","alert"]}},"NotificationStats":{"type":"object","properties":{"total":{"type":"integer","description":"Total number of notifications"},"unread":{"type":"integer","description":"Number of unread notifications"},"byType":{"type":"object","additionalProperties":{"type":"integer"},"description":"Notification count by type"}},"example":{"total":150,"unread":12,"byType":{"call":45,"assignment":30,"status":25,"message":20,"alert":15,"system":15}}},"CreateNotificationRequest":{"type":"object","required":["userId","type","title","message"],"properties":{"userId":{"type":"string","format":"uuid","description":"Target user ID"},"type":{"type":"string","enum":["call","assignment","status","message","alert","system"],"description":"Type of notification"},"title":{"type":"string","minLength":1,"maxLength":200,"description":"Notification title"},"message":{"type":"string","minLength":1,"maxLength":1000,"description":"Notification message content"},"data":{"type":"object","description":"Additional notification data"}},"example":{"userId":"770e8400-e29b-41d4-a716-446655440002","type":"alert","title":"Важное уведомление","message":"Плановое техническое обслуживание в 02:00","data":{"priority":"high"}}},"GenerateOtpRequest":{"type":"object","required":["identifier","type","purpose"],"properties":{"identifier":{"type":"string","maxLength":255,"description":"Email address or phone number","example":"user@example.com"},"type":{"type":"string","enum":["email","sms"],"description":"OTP delivery method","example":"email"},"purpose":{"type":"string","enum":["registration","login","password_reset","phone_verification","email_verification"],"description":"Purpose of the OTP code","example":"registration"}}},"ValidateOtpRequest":{"type":"object","required":["identifier","code","purpose"],"properties":{"identifier":{"type":"string","maxLength":255,"description":"Email address or phone number","example":"user@example.com"},"code":{"type":"string","pattern":"^\\d{6}$","description":"6-digit OTP code","example":"123456"},"purpose":{"type":"string","enum":["registration","login","password_reset","phone_verification","email_verification"],"description":"Purpose of the OTP code (must match the one used during generation)","example":"registration"}}},"OtpStats":{"type":"object","properties":{"totalActive":{"type":"integer","description":"Total number of active (unexpired) OTP codes","example":25},"byPurpose":{"type":"object","additionalProperties":{"type":"integer"},"description":"Active OTP count grouped by purpose","example":{"registration":10,"login":5,"password_reset":10}},"byType":{"type":"object","additionalProperties":{"type":"integer"},"description":"Active OTP count grouped by delivery type","example":{"email":20,"sms":5}}}},"PaymentOrder":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"user_id":{"type":"string","format":"uuid"},"order_type":{"type":"string","enum":["subscription","service","renewal"]},"subscription_id":{"type":"string","format":"uuid","nullable":true},"user_service_id":{"type":"string","format":"uuid","nullable":true},"tariff_plan_id":{"type":"string","format":"uuid","nullable":true},"service_id":{"type":"string","format":"uuid","nullable":true},"external_id":{"type":"string"},"npay_link_guid":{"type":"string","nullable":true},"npay_order_guid":{"type":"string","nullable":true},"payment_url":{"type":"string","nullable":true},"amount":{"type":"integer","description":"Amount in tiyyn (1 KGS = 100 tiyyn)"},"payment_amount":{"type":"integer","nullable":true},"refund_amount":{"type":"integer","default":0},"currency":{"type":"string","default":"KGS"},"status":{"type":"string","enum":["created","pending","payer_debit","payer_debit_successful","processing","completed","canceled","refunded","failed","expired"]},"channel":{"type":"string","enum":["BANK_CARD","BALANCE"],"nullable":true},"comment":{"type":"string","nullable":true},"expires_at":{"type":"string","format":"date-time","nullable":true},"created_at":{"type":"string","format":"date-time"},"updated_at":{"type":"string","format":"date-time"}}},"RefundOrder":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"payment_order_id":{"type":"string","format":"uuid"},"external_refund_id":{"type":"string"},"amount":{"type":"integer"},"currency":{"type":"string"},"status":{"type":"string","enum":["created","processing","completed","canceled","failed","expired","stuck"]},"comment":{"type":"string","nullable":true},"created_at":{"type":"string","format":"date-time"}}},"PaymentStats":{"type":"object","properties":{"totalOrders":{"type":"integer"},"completedOrders":{"type":"integer"},"failedOrders":{"type":"integer"},"canceledOrders":{"type":"integer"},"expiredOrders":{"type":"integer"},"pendingOrders":{"type":"integer"},"totalRevenue":{"type":"integer","description":"Total revenue in tiyyn"},"totalRefunds":{"type":"integer","description":"Total refunds in tiyyn"},"subscriptionOrders":{"type":"integer"},"serviceOrders":{"type":"integer"},"renewalOrders":{"type":"integer"}}},"UserQuota":{"type":"object","properties":{"id":{"type":"string","format":"uuid","description":"Quota record ID"},"userId":{"type":"string","format":"uuid","description":"User ID"},"quotaType":{"type":"string","enum":["family_members","legal_entities","connected_objects","corporate_locations","employees","emergency_calls","video_storage_days","concurrent_streams"],"description":"Type of quota"},"quotaLimit":{"type":"integer","description":"Maximum allowed usage (-1 for unlimited)"},"quotaUsed":{"type":"integer","description":"Current usage count"},"isHardLimit":{"type":"boolean","description":"Whether the limit is strictly enforced"},"overageAllowed":{"type":"boolean","description":"Whether usage beyond the limit is permitted"},"lastResetAt":{"type":"string","format":"date-time","nullable":true,"description":"Last time the quota was reset"},"createdAt":{"type":"string","format":"date-time","description":"Creation timestamp"},"updatedAt":{"type":"string","format":"date-time","description":"Last update timestamp"}},"example":{"id":"550e8400-e29b-41d4-a716-446655440000","userId":"660e8400-e29b-41d4-a716-446655440001","quotaType":"family_members","quotaLimit":5,"quotaUsed":2,"isHardLimit":true,"overageAllowed":false,"lastResetAt":null,"createdAt":"2024-01-15T10:30:00Z","updatedAt":"2024-01-15T10:30:00Z"}},"QuotaCheckResult":{"type":"object","properties":{"allowed":{"type":"boolean","description":"Whether the action is allowed under current quota"},"quotaLimit":{"type":"integer","description":"Maximum allowed usage (-1 for unlimited)"},"quotaUsed":{"type":"integer","description":"Current usage count"},"quotaRemaining":{"type":"integer","description":"Remaining quota (-1 for unlimited)"},"isUnlimited":{"type":"boolean","description":"Whether the quota is unlimited"},"message":{"type":"string","nullable":true,"description":"Additional information about the quota status"}},"example":{"allowed":true,"quotaLimit":5,"quotaUsed":2,"quotaRemaining":3,"isUnlimited":false,"message":null}},"QuotaUsageHistoryEntry":{"type":"object","properties":{"id":{"type":"string","format":"uuid","description":"Usage history entry ID"},"userId":{"type":"string","format":"uuid","description":"User ID"},"quotaType":{"type":"string","enum":["family_members","legal_entities","connected_objects","corporate_locations","employees","emergency_calls","video_storage_days","concurrent_streams"],"description":"Type of quota"},"changeAmount":{"type":"integer","description":"Amount of change (positive for increment, negative for decrement)"},"previousUsage":{"type":"integer","description":"Usage count before the change"},"newUsage":{"type":"integer","description":"Usage count after the change"},"action":{"type":"string","description":"Description of the action that caused the change"},"referenceId":{"type":"string","format":"uuid","nullable":true,"description":"ID of the related resource"},"referenceType":{"type":"string","nullable":true,"description":"Type of the related resource"},"notes":{"type":"string","nullable":true,"description":"Additional notes"},"createdAt":{"type":"string","format":"date-time","description":"Timestamp of the change"}},"example":{"id":"550e8400-e29b-41d4-a716-446655440010","userId":"660e8400-e29b-41d4-a716-446655440001","quotaType":"family_members","changeAmount":1,"previousUsage":1,"newUsage":2,"action":"add_family_member","referenceId":"770e8400-e29b-41d4-a716-446655440005","referenceType":"family_members","notes":null,"createdAt":"2024-01-15T14:00:00Z"}},"CallRating":{"type":"object","properties":{"id":{"type":"string","format":"uuid","description":"Rating ID"},"callId":{"type":"string","format":"uuid","description":"Call ID"},"clientId":{"type":"string","format":"uuid","description":"Client ID who created the rating"},"brigadeId":{"type":"string","format":"uuid","nullable":true,"description":"Brigade ID that was rated"},"rating":{"type":"integer","minimum":1,"maximum":5,"description":"Overall rating (1-5 stars)"},"comment":{"type":"string","nullable":true,"description":"Optional feedback comment"},"responseTimeRating":{"type":"integer","minimum":1,"maximum":5,"nullable":true,"description":"Rating for response time"},"professionalismRating":{"type":"integer","minimum":1,"maximum":5,"nullable":true,"description":"Rating for professionalism"},"qualityRating":{"type":"integer","minimum":1,"maximum":5,"nullable":true,"description":"Rating for service quality"},"createdAt":{"type":"string","format":"date-time","description":"Creation timestamp"},"updatedAt":{"type":"string","format":"date-time","description":"Last update timestamp"}},"example":{"id":"550e8400-e29b-41d4-a716-446655440000","callId":"660e8400-e29b-41d4-a716-446655440001","clientId":"770e8400-e29b-41d4-a716-446655440002","brigadeId":"880e8400-e29b-41d4-a716-446655440003","rating":5,"comment":"Отличная работа, быстро приехали!","responseTimeRating":5,"professionalismRating":5,"qualityRating":5,"createdAt":"2024-01-15T10:30:00Z","updatedAt":"2024-01-15T10:30:00Z"}},"CreateRatingRequest":{"type":"object","required":["callId","rating"],"properties":{"callId":{"type":"string","format":"uuid","description":"ID of the completed call to rate"},"rating":{"type":"integer","minimum":1,"maximum":5,"description":"Overall rating (1-5 stars)"},"comment":{"type":"string","maxLength":1000,"description":"Optional feedback comment"},"responseTimeRating":{"type":"integer","minimum":1,"maximum":5,"description":"Optional rating for response time"},"professionalismRating":{"type":"integer","minimum":1,"maximum":5,"description":"Optional rating for professionalism"},"qualityRating":{"type":"integer","minimum":1,"maximum":5,"description":"Optional rating for service quality"}},"example":{"callId":"660e8400-e29b-41d4-a716-446655440001","rating":5,"comment":"Отличная работа, быстро приехали!","responseTimeRating":5,"professionalismRating":5,"qualityRating":5}},"UpdateRatingRequest":{"type":"object","properties":{"rating":{"type":"integer","minimum":1,"maximum":5,"description":"Overall rating (1-5 stars)"},"comment":{"type":"string","maxLength":1000,"description":"Optional feedback comment"},"responseTimeRating":{"type":"integer","minimum":1,"maximum":5,"description":"Optional rating for response time"},"professionalismRating":{"type":"integer","minimum":1,"maximum":5,"description":"Optional rating for professionalism"},"qualityRating":{"type":"integer","minimum":1,"maximum":5,"description":"Optional rating for service quality"}},"example":{"rating":4,"comment":"Хорошо, но можно было быстрее"}},"BrigadeAverageRating":{"type":"object","properties":{"averageRating":{"type":"number","format":"float","description":"Average overall rating"},"totalRatings":{"type":"integer","description":"Total number of ratings"},"ratingBreakdown":{"type":"object","properties":{"responseTime":{"type":"number","format":"float","description":"Average response time rating"},"professionalism":{"type":"number","format":"float","description":"Average professionalism rating"},"quality":{"type":"number","format":"float","description":"Average quality rating"}}}},"example":{"averageRating":4.5,"totalRatings":120,"ratingBreakdown":{"responseTime":4.3,"professionalism":4.7,"quality":4.6}}},"GeneratedReport":{"type":"object","properties":{"id":{"type":"string","format":"uuid","example":"123e4567-e89b-12d3-a456-426614174000"},"type":{"type":"string","enum":["daily","monthly","custom","export"],"example":"daily","description":"Report type"},"dateRangeStart":{"type":"string","format":"date","example":"2026-01-01"},"dateRangeEnd":{"type":"string","format":"date","example":"2026-01-31"},"fileUrl":{"type":"string","format":"uri","example":"https://s3.amazonaws.com/reports/2026/01/uuid-daily-report-2026-01-23.json","description":"URL to download the report file"},"fileSize":{"type":"integer","example":15420,"description":"File size in bytes"},"generatedBy":{"type":"string","format":"uuid","nullable":true,"example":"123e4567-e89b-12d3-a456-426614174001"},"generatedByName":{"type":"string","nullable":true,"example":"John Doe"},"generatedByEmail":{"type":"string","format":"email","nullable":true,"example":"john.doe@example.com"},"status":{"type":"string","enum":["pending","processing","completed","failed"],"example":"completed"},"errorMessage":{"type":"string","nullable":true,"example":null,"description":"Error message if report generation failed"},"metadata":{"type":"object","nullable":true,"description":"Additional metadata (filters, export type, etc.)","example":{"exportType":"calls","format":"csv","recordCount":150}},"createdAt":{"type":"string","format":"date-time","example":"2026-01-23T14:30:00Z"},"updatedAt":{"type":"string","format":"date-time","example":"2026-01-23T14:30:05Z"},"headers":{"type":"array","items":{"type":"string"},"description":"Column header labels"},"rows":{"type":"array","items":{"type":"array","items":{"type":"string"}},"description":"Data rows (each row is an array of string values)"},"total":{"type":"integer","description":"Total number of data rows"},"generatedAt":{"type":"string","format":"date-time","description":"ISO timestamp when the report was generated"},"stats":{"type":"object","additionalProperties":{"oneOf":[{"type":"string"},{"type":"integer"}]},"description":"Summary statistics (content varies by report type)"}}},"CallsReportData":{"type":"object","properties":{"totalCalls":{"type":"integer","example":150},"completedCalls":{"type":"integer","example":120},"cancelledCalls":{"type":"integer","example":15},"pendingCalls":{"type":"integer","example":15},"averageResponseTime":{"type":"number","format":"float","example":25.5},"totalRevenue":{"type":"number","format":"decimal","example":15750},"callsByStatus":{"type":"array","items":{"type":"object","properties":{"status":{"type":"string"},"count":{"type":"integer"}}}},"callsByType":{"type":"array","items":{"type":"object","properties":{"type":{"type":"string"},"count":{"type":"integer"}}}},"callsByPriority":{"type":"array","items":{"type":"object","properties":{"priority":{"type":"string"},"count":{"type":"integer"}}}},"topClients":{"type":"array","items":{"type":"object","properties":{"clientId":{"type":"string","format":"uuid"},"clientName":{"type":"string"},"callCount":{"type":"integer"},"totalSpent":{"type":"number","format":"decimal"}}}},"brigadePerformance":{"type":"array","items":{"type":"object","properties":{"brigadeId":{"type":"string","format":"uuid"},"brigadeName":{"type":"string"},"callsHandled":{"type":"integer"},"averageResponseTime":{"type":"number","format":"float"},"completionRate":{"type":"number","format":"float"}}}}}},"UsersReportData":{"type":"object","properties":{"totalUsers":{"type":"integer","example":500},"activeUsers":{"type":"integer","example":450},"newUsersThisPeriod":{"type":"integer","example":25},"usersByRole":{"type":"array","items":{"type":"object","properties":{"role":{"type":"string"},"count":{"type":"integer"}}}},"usersByStatus":{"type":"array","items":{"type":"object","properties":{"status":{"type":"string"},"count":{"type":"integer"}}}}}},"RevenueReportData":{"type":"object","properties":{"totalRevenue":{"type":"number","format":"decimal","example":25750},"averageCallValue":{"type":"number","format":"decimal","example":125.5},"revenueByMonth":{"type":"array","items":{"type":"object","properties":{"month":{"type":"string","example":"2024-01"},"revenue":{"type":"number","format":"decimal"},"callCount":{"type":"integer"}}}},"revenueByTariff":{"type":"array","items":{"type":"object","properties":{"tariffId":{"type":"string","format":"uuid"},"tariffName":{"type":"string"},"revenue":{"type":"number","format":"decimal"},"callCount":{"type":"integer"}}}},"topRevenueClients":{"type":"array","items":{"type":"object","properties":{"clientId":{"type":"string","format":"uuid"},"clientName":{"type":"string"},"totalSpent":{"type":"number","format":"decimal"},"callCount":{"type":"integer"}}}}}},"WorkSchedulesReportData":{"type":"object","properties":{"totalWorkDays":{"type":"integer","example":20,"description":"Total number of work days in the period"},"totalWorkingHours":{"type":"number","format":"float","example":160.5,"description":"Total working hours across all schedules"},"averageWorkingHours":{"type":"number","format":"float","example":8.025,"description":"Average working hours per day"},"totalLunchHours":{"type":"number","format":"float","example":20,"description":"Total lunch break hours"},"schedulesByStatus":{"type":"array","description":"Work schedules grouped by status","items":{"type":"object","properties":{"status":{"type":"string","enum":["not_started","working","on_break","finished"]},"count":{"type":"integer"}}}},"brigadeWorkSummary":{"type":"array","description":"Work summary per brigade","items":{"type":"object","properties":{"brigadeId":{"type":"string","format":"uuid"},"brigadeName":{"type":"string"},"workDays":{"type":"integer"},"totalHours":{"type":"number","format":"float"},"averageHours":{"type":"number","format":"float"}}}},"scheduleDetails":{"type":"array","description":"Detailed work schedule information with start/end documentation","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"brigadeId":{"type":"string","format":"uuid"},"brigadeName":{"type":"string"},"carId":{"type":"string","format":"uuid"},"carLicensePlate":{"type":"string"},"workDate":{"type":"string","format":"date"},"startTime":{"type":"string","format":"date-time","nullable":true},"endTime":{"type":"string","format":"date-time","nullable":true},"startImageUrls":{"type":"array","description":"Array of photo URLs when starting work","items":{"type":"string","format":"uri"},"example":["https://storage.example.com/work/start1.jpg","https://storage.example.com/work/start2.jpg"]},"startComment":{"type":"string","nullable":true,"description":"Comment when starting work","example":"Starting morning shift"},"endImageUrls":{"type":"array","description":"Array of photo URLs when ending work","items":{"type":"string","format":"uri"},"example":["https://storage.example.com/work/end1.jpg"]},"endComment":{"type":"string","nullable":true,"description":"Comment when ending work","example":"Completed all tasks"},"status":{"type":"string","enum":["not_started","working","on_break","finished"]},"totalHours":{"type":"integer","nullable":true,"description":"Total hours worked (in minutes)"},"lunchDuration":{"type":"integer","nullable":true,"description":"Lunch break duration (in minutes)"},"workingHours":{"type":"integer","nullable":true,"description":"Actual working hours excluding lunch (in minutes)"}}}}}},"TariffsReportData":{"type":"object","properties":{"totalTariffPlans":{"type":"integer","example":5},"activeTariffPlans":{"type":"integer","example":4},"totalSubscriptions":{"type":"integer","example":120},"activeSubscriptions":{"type":"integer","example":95},"subscriptionsByTariff":{"type":"array","items":{"type":"object","properties":{"tariffId":{"type":"string","format":"uuid"},"tariffName":{"type":"string"},"planType":{"type":"string","enum":["individual","family","corporate"]},"price":{"type":"number","format":"decimal"},"billingPeriod":{"type":"string","enum":["monthly","quarterly","yearly","one_time"]},"subscriberCount":{"type":"integer"},"activeCount":{"type":"integer"},"revenue":{"type":"number","format":"decimal"}}}},"subscriptionsByStatus":{"type":"array","items":{"type":"object","properties":{"status":{"type":"string","enum":["active","suspended","cancelled","expired"]},"count":{"type":"integer"}}}},"subscriptionsByPlanType":{"type":"array","items":{"type":"object","properties":{"planType":{"type":"string"},"count":{"type":"integer"}}}},"subscriptionsByBillingPeriod":{"type":"array","items":{"type":"object","properties":{"billingPeriod":{"type":"string"},"count":{"type":"integer"}}}},"autoRenewalStats":{"type":"object","properties":{"autoRenewalCount":{"type":"integer"},"manualRenewalCount":{"type":"integer"}}},"paymentMethodDistribution":{"type":"array","items":{"type":"object","properties":{"paymentMethod":{"type":"string"},"count":{"type":"integer"}}}}}},"QuotasReportData":{"type":"object","properties":{"totalUsersWithQuotas":{"type":"integer","example":80},"quotasByType":{"type":"array","items":{"type":"object","properties":{"quotaType":{"type":"string"},"totalUsers":{"type":"integer"},"avgUsagePercent":{"type":"number","format":"float"},"maxUsage":{"type":"integer"},"usersAtLimit":{"type":"integer"},"usersOverLimit":{"type":"integer"}}}},"tariffQuotaLimits":{"type":"array","items":{"type":"object","properties":{"tariffName":{"type":"string"},"quotaType":{"type":"string"},"quotaLimit":{"type":"integer"},"isHardLimit":{"type":"boolean"},"overageAllowed":{"type":"boolean"},"overagePrice":{"type":"number","format":"decimal","nullable":true}}}},"topClientsByCallCount":{"type":"array","items":{"type":"object","properties":{"clientId":{"type":"string","format":"uuid"},"clientName":{"type":"string"},"tariffName":{"type":"string"},"callCount":{"type":"integer"},"quotaLimit":{"type":"integer"},"usagePercent":{"type":"number","format":"float"}}}},"clientsExceedingLimits":{"type":"array","items":{"type":"object","properties":{"clientId":{"type":"string","format":"uuid"},"clientName":{"type":"string"},"quotaType":{"type":"string"},"quotaLimit":{"type":"integer"},"quotaUsed":{"type":"integer"},"overageAmount":{"type":"integer"}}}}}},"RouteCoordinate":{"type":"object","properties":{"latitude":{"type":"number","example":42.8826},"longitude":{"type":"number","example":74.6156}},"required":["latitude","longitude"]},"RouteResult":{"type":"object","properties":{"coordinates":{"type":"array","items":{"$ref":"#/components/schemas/RouteCoordinate"},"description":"Array of coordinates forming the road path"},"distance":{"type":"number","description":"Total route distance in meters","example":3450},"duration":{"type":"number","description":"Estimated travel time in seconds","example":420}},"required":["coordinates","distance","duration"]},"ServiceApplication":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"user_id":{"type":"string","format":"uuid"},"service_id":{"type":"string","format":"uuid"},"status":{"type":"string","enum":["pending","approved","rejected","cancelled"]},"contract_number":{"type":"string","nullable":true},"contract_signed_at":{"type":"string","format":"date-time","nullable":true},"contract_file_url":{"type":"string","nullable":true},"payment_confirmed":{"type":"boolean"},"payment_amount":{"type":"number","nullable":true},"payment_date":{"type":"string","format":"date-time","nullable":true},"payment_reference":{"type":"string","nullable":true},"reviewed_by":{"type":"string","format":"uuid","nullable":true},"reviewed_at":{"type":"string","format":"date-time","nullable":true},"rejection_reason":{"type":"string","nullable":true},"admin_notes":{"type":"string","nullable":true},"created_at":{"type":"string","format":"date-time"},"updated_at":{"type":"string","format":"date-time"}}},"SupportConversation":{"type":"object","properties":{"id":{"type":"string","format":"uuid","description":"Conversation ID"},"clientId":{"type":"string","format":"uuid","description":"Client user ID"},"operatorId":{"type":"string","format":"uuid","nullable":true,"description":"Assigned operator user ID"},"legalEntityId":{"type":"string","format":"uuid","nullable":true,"description":"Legal entity ID for shared corporate conversations"},"status":{"type":"string","enum":["active","waiting","closed"],"description":"Conversation status"},"subject":{"type":"string","nullable":true,"description":"Conversation subject"},"priority":{"type":"string","enum":["low","normal","high","urgent"],"description":"Conversation priority"},"startedAt":{"type":"string","format":"date-time","description":"When the conversation started"},"endedAt":{"type":"string","format":"date-time","nullable":true,"description":"When the conversation ended"},"lastMessageAt":{"type":"string","format":"date-time","description":"Timestamp of the last message"},"createdAt":{"type":"string","format":"date-time","description":"Creation timestamp"},"updatedAt":{"type":"string","format":"date-time","description":"Last update timestamp"}},"example":{"id":"550e8400-e29b-41d4-a716-446655440000","clientId":"660e8400-e29b-41d4-a716-446655440001","operatorId":"770e8400-e29b-41d4-a716-446655440002","legalEntityId":null,"status":"active","subject":"Чат с Иван Иванов","priority":"normal","startedAt":"2024-01-15T10:00:00Z","endedAt":null,"lastMessageAt":"2024-01-15T10:30:00Z","createdAt":"2024-01-15T10:00:00Z","updatedAt":"2024-01-15T10:30:00Z"}},"ConversationWithDetails":{"allOf":[{"$ref":"#/components/schemas/SupportConversation"},{"type":"object","properties":{"client":{"type":"object","description":"Client details","properties":{"first_name":{"type":"string"},"last_name":{"type":"string"},"email":{"type":"string","format":"email"},"phone":{"type":"string","nullable":true}}},"operator":{"type":"object","nullable":true,"description":"Assigned operator details","properties":{"first_name":{"type":"string"},"last_name":{"type":"string"},"role":{"type":"string","enum":["dispatcher","admin"]}}},"unreadCount":{"type":"integer","description":"Number of unread messages in the conversation"},"lastMessage":{"type":"object","nullable":true,"description":"Preview of the last message","properties":{"message":{"type":"string"},"messageType":{"type":"string","enum":["text","file","image","system"]},"createdAt":{"type":"string","format":"date-time"}}}}}]},"SupportMessage":{"type":"object","properties":{"id":{"type":"string","format":"uuid","description":"Message ID"},"conversationId":{"type":"string","format":"uuid","description":"Conversation ID"},"senderId":{"type":"string","format":"uuid","nullable":true,"description":"Sender user ID (null for system messages)"},"message":{"type":"string","description":"Message content"},"messageType":{"type":"string","enum":["text","file","image","system"],"description":"Type of the message"},"fileUrl":{"type":"string","format":"uri","nullable":true,"description":"URL of attached file (for file/image messages)"},"isRead":{"type":"boolean","description":"Whether the message has been read"},"createdAt":{"type":"string","format":"date-time","description":"Creation timestamp"},"sender":{"type":"object","description":"Sender details","properties":{"first_name":{"type":"string","description":"Sender first name (or \"System\" for system messages)"},"last_name":{"type":"string","description":"Sender last name"},"role":{"type":"string","enum":["client","dispatcher","admin","system"],"description":"Sender role"}}}},"example":{"id":"880e8400-e29b-41d4-a716-446655440003","conversationId":"550e8400-e29b-41d4-a716-446655440000","senderId":"660e8400-e29b-41d4-a716-446655440001","message":"Здравствуйте, мне нужна помощь","messageType":"text","fileUrl":null,"isRead":false,"createdAt":"2024-01-15T10:30:00Z","sender":{"first_name":"Иван","last_name":"Иванов","role":"client"}}},"StartConversationRequest":{"type":"object","properties":{"subject":{"type":"string","minLength":1,"maxLength":200,"description":"Conversation subject. If not provided, auto-generated from user's name."},"priority":{"type":"string","enum":["low","normal","high","urgent"],"default":"normal","description":"Conversation priority level"}},"example":{"subject":"Вопрос по подписке","priority":"normal"}},"SendMessageRequest":{"type":"object","required":["message"],"properties":{"message":{"type":"string","description":"Message content"},"messageType":{"type":"string","enum":["text","file","image"],"default":"text","description":"Type of message being sent"},"fileUrl":{"type":"string","format":"uri","description":"URL of attached file (required for file/image messages)"}},"example":{"message":"Здравствуйте, мне нужна помощь с подпиской","messageType":"text"}},"TariffPlan":{"type":"object","properties":{"id":{"type":"string","format":"uuid","example":"123e4567-e89b-12d3-a456-426614174000"},"name":{"type":"string","example":"individual_basic"},"display_name":{"type":"string","example":"Базовый"},"description":{"type":"string","nullable":true,"example":"Basic plan description"},"price":{"type":"number","format":"decimal","example":999},"currency":{"type":"string","example":"KGS","default":"KGS"},"billing_period":{"type":"string","enum":["monthly","quarterly","yearly","one_time"],"example":"monthly"},"plan_type":{"type":"string","enum":["individual","family","corporate"],"example":"individual"},"priority_level":{"type":"integer","example":3,"default":3},"response_time_minutes":{"type":"integer","example":20,"default":15},"is_active":{"type":"boolean","example":true,"default":true},"is_featured":{"type":"boolean","example":false,"default":false},"sort_order":{"type":"integer","example":0,"default":0},"created_at":{"type":"string","format":"date-time"},"updated_at":{"type":"string","format":"date-time"},"deleted_at":{"type":"string","format":"date-time","nullable":true},"quotas":{"type":"array","items":{"type":"object","properties":{"quotaType":{"type":"string","enum":["family_members","legal_entities","connected_objects","corporate_locations","employees","emergency_calls","video_storage_days","concurrent_streams","ambulance_calls","cash_collection_calls","personal_security_calls"],"example":"family_members"},"quotaLimit":{"type":"integer","example":1},"isHardLimit":{"type":"boolean","example":true},"overageAllowed":{"type":"boolean","example":false},"overagePrice":{"type":"number","format":"decimal","nullable":true,"example":null}}}}}},"Service":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"name":{"type":"string"},"displayName":{"type":"string"},"description":{"type":"string"},"serviceType":{"type":"string","enum":["security_monitoring","fire_alarm","video_surveillance","access_control","medical_alert","panic_button","smart_home_integration","mobile_app_access"]},"price":{"type":"number"},"currency":{"type":"string"},"billingPeriod":{"type":"string","enum":["monthly","quarterly","yearly","one_time"]},"isAddon":{"type":"boolean"},"requiresPlan":{"type":"boolean"},"quotas":{"type":"array","items":{"type":"object","properties":{"quotaType":{"type":"string"},"quotaAddition":{"type":"integer"}}}}}},"UserService":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"userId":{"type":"string","format":"uuid"},"serviceId":{"type":"string","format":"uuid"},"startDate":{"type":"string","format":"date"},"endDate":{"type":"string","format":"date"},"autoRenewal":{"type":"boolean"},"isActive":{"type":"boolean"}}},"UserSubscription":{"type":"object","properties":{"id":{"type":"string","format":"uuid","example":"123e4567-e89b-12d3-a456-426614174000"},"user_id":{"type":"string","format":"uuid"},"tariff_plan_id":{"type":"string","format":"uuid"},"start_date":{"type":"string","format":"date-time"},"end_date":{"type":"string","format":"date-time","nullable":true},"auto_renewal":{"type":"boolean","default":true},"payment_method":{"type":"string","enum":["elqr","card","cash","bank_transfer","mobile_payment"],"example":"card"},"status":{"type":"string","enum":["active","cancelled","expired","suspended"],"example":"active"},"created_at":{"type":"string","format":"date-time"},"updated_at":{"type":"string","format":"date-time"},"plan_name":{"type":"string","example":"individual_basic"},"plan_display_name":{"type":"string","example":"Базовый"},"plan_price":{"type":"number","format":"decimal","example":999},"billing_period":{"type":"string","enum":["monthly","quarterly","yearly","one_time"],"example":"monthly"},"plan_quotas":{"type":"array","items":{"type":"object","properties":{"quotaType":{"type":"string","example":"family_members"},"quotaLimit":{"type":"integer","example":1}}}}}},"WorkSchedule":{"type":"object","properties":{"id":{"type":"string","format":"uuid","description":"Work schedule ID"},"brigadeId":{"type":"string","format":"uuid","description":"Brigade ID"},"carId":{"type":"string","format":"uuid","nullable":true,"description":"Assigned car ID"},"workDate":{"type":"string","format":"date","description":"Work date"},"startTime":{"type":"string","format":"date-time","nullable":true,"description":"Work start time"},"endTime":{"type":"string","format":"date-time","nullable":true,"description":"Work end time"},"lunchStart":{"type":"string","format":"date-time","nullable":true,"description":"Lunch break start time"},"lunchEnd":{"type":"string","format":"date-time","nullable":true,"description":"Lunch break end time"},"imageUrl":{"type":"string","format":"uri","nullable":true,"description":"Image URL"},"comment":{"type":"string","nullable":true,"description":"Comment"},"status":{"type":"string","enum":["not_started","working","on_break","finished"],"description":"Current work status"}},"example":{"id":"550e8400-e29b-41d4-a716-446655440000","brigadeId":"660e8400-e29b-41d4-a716-446655440001","carId":"770e8400-e29b-41d4-a716-446655440002","workDate":"2024-01-15","startTime":"2024-01-15T08:00:00Z","endTime":"2024-01-15T17:00:00Z","lunchStart":"2024-01-15T12:00:00Z","lunchEnd":"2024-01-15T13:00:00Z","imageUrl":null,"comment":null,"status":"finished"}},"WorkScheduleDetailed":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"brigadeId":{"type":"string","format":"uuid"},"carId":{"type":"string","format":"uuid","nullable":true},"workDate":{"type":"string","format":"date"},"startTime":{"type":"string","format":"date-time","nullable":true},"endTime":{"type":"string","format":"date-time","nullable":true},"lunchStart":{"type":"string","format":"date-time","nullable":true},"lunchEnd":{"type":"string","format":"date-time","nullable":true},"startImageUrls":{"type":"array","items":{"type":"string","format":"uri"},"description":"Images taken at work start"},"startComment":{"type":"string","nullable":true,"description":"Comment at work start"},"endImageUrls":{"type":"array","items":{"type":"string","format":"uri"},"description":"Images taken at work end"},"endComment":{"type":"string","nullable":true,"description":"Comment at work end"},"status":{"type":"string","enum":["not_started","working","on_break","finished"]},"userName":{"type":"string","description":"Full name of the brigade member"},"userEmail":{"type":"string","format":"email","description":"Email of the brigade member"},"brigadeName":{"type":"string","description":"Name of the brigade"},"carLicensePlate":{"type":"string","nullable":true,"description":"Car license plate"},"carModel":{"type":"string","nullable":true,"description":"Car model"},"totalHours":{"type":"number","nullable":true,"description":"Total hours worked (including lunch)"},"lunchDuration":{"type":"number","nullable":true,"description":"Lunch duration in hours"},"workingHours":{"type":"number","nullable":true,"description":"Net working hours (excluding lunch)"}}},"WorkStatus":{"type":"object","properties":{"status":{"type":"string","enum":["not_started","working","on_break","finished"],"description":"Current work status"},"workScheduleId":{"type":"string","format":"uuid","nullable":true,"description":"Work schedule ID (if exists)"},"startTime":{"type":"string","format":"date-time","nullable":true,"description":"Work start time (if started)"},"lunchStart":{"type":"string","format":"date-time","nullable":true,"description":"Lunch start time (if on break)"},"lunchEnd":{"type":"string","format":"date-time","nullable":true,"description":"Lunch end time (if break ended)"}},"example":{"status":"working","workScheduleId":"550e8400-e29b-41d4-a716-446655440000","startTime":"2024-01-15T08:00:00Z","lunchStart":null,"lunchEnd":null}},"StartWorkRequest":{"type":"object","properties":{"carId":{"type":"string","format":"uuid","description":"Car ID to assign for the work day"},"imageUrls":{"type":"array","items":{"type":"string","format":"uri"},"description":"Array of image URLs for work documentation"},"comment":{"type":"string","maxLength":500,"description":"Additional comments"}},"example":{"carId":"770e8400-e29b-41d4-a716-446655440002","imageUrls":["https://example.com/photo1.jpg"],"comment":"Начало смены, все в порядке"}},"WorkActionRequest":{"type":"object","required":["type"],"properties":{"type":{"type":"string","enum":["start","end"],"description":"Action type - start or end work"},"carId":{"type":"string","format":"uuid","description":"Car ID (optional)"},"imageUrls":{"type":"array","items":{"type":"string","format":"uri"},"description":"Array of image URLs for work documentation"},"comment":{"type":"string","maxLength":500,"description":"Additional comments"}},"example":{"type":"start","carId":"770e8400-e29b-41d4-a716-446655440002","imageUrls":["https://example.com/photo1.jpg"],"comment":"Начало смены"}},"EmergencyExitRequest":{"type":"object","required":["reason"],"properties":{"reason":{"type":"string","enum":["medical_emergency","security_threat","equipment_failure","natural_disaster","family_emergency","vehicle_breakdown","other"],"description":"Emergency exit reason"},"description":{"type":"string","maxLength":500,"description":"Detailed description of the emergency situation"},"location":{"type":"object","properties":{"lat":{"type":"number","minimum":-90,"maximum":90,"description":"Latitude"},"lng":{"type":"number","minimum":-180,"maximum":180,"description":"Longitude"}},"description":"Current GPS location for emergency response"}},"example":{"reason":"vehicle_breakdown","description":"Двигатель заглох на трассе","location":{"lat":42.8746,"lng":74.5698}}},"EmergencyExitRecord":{"type":"object","properties":{"id":{"type":"string","format":"uuid","description":"Emergency exit record ID"},"brigadeId":{"type":"string","format":"uuid"},"userId":{"type":"string","format":"uuid"},"reason":{"type":"string","enum":["medical_emergency","security_threat","equipment_failure","natural_disaster","family_emergency","vehicle_breakdown","other"]},"description":{"type":"string","nullable":true},"exitTime":{"type":"string","format":"date-time"},"resolvedAt":{"type":"string","format":"date-time","nullable":true},"resolutionNotes":{"type":"string","nullable":true},"brigade":{"type":"object","properties":{"name":{"type":"string"}}},"user":{"type":"object","properties":{"firstName":{"type":"string"},"lastName":{"type":"string"},"email":{"type":"string","format":"email"}}}}},"ResolveEmergencyExitRequest":{"type":"object","properties":{"resolutionNotes":{"type":"string","maxLength":1000,"description":"Notes about the resolution"}},"example":{"resolutionNotes":"Машина отбуксирована, бригада пересажена на резервный транспорт"}},"GeoPolygon":{"type":"object","required":["type","coordinates"],"properties":{"type":{"type":"string","enum":["Polygon"],"example":"Polygon"},"coordinates":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"number"},"minItems":2,"maxItems":2}},"example":[[[74.5898,42.8746],[74.5998,42.8746],[74.5998,42.8846],[74.5898,42.8846],[74.5898,42.8746]]],"description":"Array of coordinate rings. First ring is exterior boundary."}}},"Zone":{"type":"object","properties":{"id":{"type":"string","format":"uuid","example":"550e8400-e29b-41d4-a716-446655440000"},"name":{"type":"string","example":"Downtown Bishkek"},"description":{"type":"string","example":"Central business district coverage area"},"polygon":{"$ref":"#/components/schemas/GeoPolygon"},"isActive":{"type":"boolean","example":true},"createdAt":{"type":"string","format":"date-time"},"updatedAt":{"type":"string","format":"date-time"}}},"ZoneWithStats":{"allOf":[{"$ref":"#/components/schemas/Zone"},{"type":"object","properties":{"stats":{"type":"object","properties":{"brigadeCount":{"type":"integer","example":3},"tariffCount":{"type":"integer","example":2},"activeCallsCount":{"type":"integer","example":5}}}}}]},"CreateZoneRequest":{"type":"object","required":["name","polygon"],"properties":{"name":{"type":"string","minLength":2,"maxLength":100,"example":"Downtown Bishkek"},"description":{"type":"string","maxLength":500,"example":"Central business district coverage area"},"polygon":{"$ref":"#/components/schemas/GeoPolygon"},"isActive":{"type":"boolean","default":true,"example":true}}},"UpdateZoneRequest":{"type":"object","properties":{"name":{"type":"string","minLength":2,"maxLength":100,"example":"Updated Zone Name"},"description":{"type":"string","maxLength":500,"example":"Updated description"},"polygon":{"$ref":"#/components/schemas/GeoPolygon"},"isActive":{"type":"boolean","example":false}}},"PointInZoneResult":{"type":"object","properties":{"isInside":{"type":"boolean","example":true},"zone":{"$ref":"#/components/schemas/Zone"},"distance":{"type":"number","example":0,"description":"Distance to zone boundary (0 if inside, meters if outside)"}}},"CORAlert":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"user_id":{"type":"string","format":"uuid"},"object_id":{"type":"string","format":"uuid"},"shift_id":{"type":"string","format":"uuid","nullable":true},"type":{"type":"string","enum":["panic","overdue_report","geofence_breach","gps_anomaly"]},"status":{"type":"string","enum":["active","acknowledged","resolved","false_alarm"]},"latitude":{"type":"number","format":"double"},"longitude":{"type":"number","format":"double"},"acknowledged_by":{"type":"string","format":"uuid","nullable":true},"acknowledged_at":{"type":"string","format":"date-time","nullable":true},"resolved_by":{"type":"string","format":"uuid","nullable":true},"resolved_at":{"type":"string","format":"date-time","nullable":true},"resolution_note":{"type":"string","nullable":true},"created_at":{"type":"string","format":"date-time"},"user_name":{"type":"string"},"object_name":{"type":"string"},"location_trail":{"type":"array","items":{"type":"object","properties":{"lat":{"type":"number"},"lng":{"type":"number"},"at":{"type":"string","format":"date-time"}}}}}},"TriggerAlertRequest":{"type":"object","required":["objectId","latitude","longitude"],"properties":{"objectId":{"type":"string","format":"uuid"},"shiftId":{"type":"string","format":"uuid"},"latitude":{"type":"number","minimum":-90,"maximum":90},"longitude":{"type":"number","minimum":-180,"maximum":180},"type":{"type":"string","enum":["panic","overdue_report","geofence_breach","gps_anomaly"]}}},"BroadcastMessageRequest":{"type":"object","required":["messageType"],"properties":{"messageType":{"type":"string","enum":["power_outage","camera_failure","intruder_detected","fire_alarm","equipment_failure","other"],"description":"Predefined message type. Russian text is resolved server-side:\npower_outage → \"Отключение электричества\",\ncamera_failure → \"Камера не работает\",\nintruder_detected → \"Обнаружен нарушитель\",\nfire_alarm → \"Сработала пожарная сигнализация\",\nequipment_failure → \"Поломка оборудования\",\nother → uses customMessage field.\n"},"customMessage":{"type":"string","maxLength":200,"description":"Required when messageType is 'other'. Ignored otherwise."}}},"CORCoverageRow":{"type":"object","description":"One active object for the chosen night, staffed or not.","properties":{"object_id":{"type":"string","format":"uuid"},"object_name":{"type":"string"},"object_type":{"type":"string","enum":["azs","nb","gns","parking","office","other"]},"object_address":{"type":"string","nullable":true},"region":{"type":"string","nullable":true},"planned_start":{"type":"string","format":"date-time","nullable":true,"description":"When the shift was due to open, from the object's report_start_time."},"shift_id":{"type":"string","format":"uuid","nullable":true},"user_id":{"type":"string","format":"uuid","nullable":true},"first_name":{"type":"string","nullable":true},"last_name":{"type":"string","nullable":true},"phone":{"type":"string","nullable":true},"started_at":{"type":"string","format":"date-time","nullable":true},"ended_at":{"type":"string","format":"date-time","nullable":true},"shift_status":{"type":"string","nullable":true,"enum":["active","completed","abandoned"]},"is_outside_geofence":{"type":"boolean","nullable":true},"late_minutes":{"type":"integer","description":"Minutes past the planned start. For an absent object, minutes elapsed since it was due."},"last_activity":{"type":"string","format":"date-time","nullable":true},"status":{"type":"string","enum":["on_shift","late","absent","expected","completed"],"description":"on_shift — На смене; late — Опоздал; absent — Не вышел; expected — Ожидается; completed — Завершена.\n"},"is_problem":{"type":"boolean","description":"True for late and absent — the rows sorted to the top."}}},"CORReportMatrixCell":{"type":"object","properties":{"slot":{"type":"string","format":"date-time"},"status":{"type":"string","enum":["on_time","late","pending","missed","no_shift","not_applicable"],"description":"on_time — sent within the grace period; late — sent after it; pending — the slot has not arrived yet; missed — the slot passed on a staffed object with no doklad; no_shift — nobody was on duty; not_applicable — this object does not report at this time.\n"},"report_id":{"type":"string","format":"uuid"},"situation":{"type":"string","enum":["calm","suspicious","emergency"]},"actual_at":{"type":"string","format":"date-time"},"delay_minutes":{"type":"integer"}}},"CORCoverageSettings":{"type":"object","properties":{"shiftLateGraceMinutes":{"type":"integer","minimum":0,"maximum":720,"description":"Minutes after the planned start before a shift counts as late."},"reportLateGraceMinutes":{"type":"integer","minimum":0,"maximum":720,"description":"Minutes after a slot before a doklad counts as late."}}},"CORAnalyticsRow":{"type":"object","description":"One ranked line — an object or an employee.","properties":{"key":{"type":"string","format":"uuid"},"label":{"type":"string"},"region":{"type":"string","nullable":true},"expected":{"type":"integer","description":"Dokladi owed. For an object: nights in range x slots per night from its configuration. For an employee: the slots owed by the objects they staffed on the nights they worked — not every night in the period, so someone who covered two nights of thirty is not scored as though they missed the other twenty-eight.\n"},"on_time":{"type":"integer"},"late":{"type":"integer"},"missed":{"type":"integer","description":"Derived (expected - on_time - late), clamped at zero."},"extra":{"type":"integer","description":"Ad-hoc dokladi matching no slot. Excluded from on_time_percent."},"on_time_percent":{"type":"integer","nullable":true},"avg_late_minutes":{"type":"number"},"nights_expected":{"type":"integer"},"nights_opened":{"type":"integer"},"unopened_shifts":{"type":"integer"},"late_openings":{"type":"integer"},"alerts":{"type":"integer"}}},"CORDashboardMetrics":{"type":"object","properties":{"active_shifts":{"type":"integer"},"objects_on_shift":{"type":"integer"},"total_objects":{"type":"integer"},"overdue_reports":{"type":"integer"},"active_alerts":{"type":"integer"},"total_alerts_today":{"type":"integer"},"total_reports_today":{"type":"integer"},"late_reports_today":{"type":"integer"},"total_operators":{"type":"integer","description":"Total number of COR operators (all roles)"}}},"CORAnalytics":{"type":"object","properties":{"shifts":{"type":"object","properties":{"total":{"type":"integer"},"avg_duration_hours":{"type":"number"}}},"reports":{"type":"object","properties":{"total":{"type":"integer"},"on_time":{"type":"integer"},"late":{"type":"integer"},"on_time_rate":{"type":"integer"}}},"alerts_by_type":{"type":"array","items":{"type":"object","properties":{"type":{"type":"string"},"count":{"type":"string"}}}},"alerts_by_object":{"type":"array","items":{"type":"object","properties":{"object_name":{"type":"string"},"count":{"type":"string"}}}},"reports_by_situation":{"type":"array","items":{"type":"object","properties":{"situation":{"type":"string"},"count":{"type":"string"}}}}}},"CORObject":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"name":{"type":"string","maxLength":255},"type":{"type":"string","enum":["azs","nb","gns","parking","office","other"]},"address":{"type":"string"},"latitude":{"type":"number","format":"double"},"longitude":{"type":"number","format":"double"},"geofence_radius_m":{"type":"integer","default":100},"report_interval_minutes":{"type":"integer","default":120},"report_start_time":{"type":"string","example":"22:00"},"report_end_time":{"type":"string","example":"06:00"},"is_active":{"type":"boolean","default":true},"created_at":{"type":"string","format":"date-time"},"updated_at":{"type":"string","format":"date-time"},"created_by":{"type":"string","format":"uuid"},"updated_by":{"type":"string","format":"uuid"}}},"CreateCORObjectRequest":{"type":"object","required":["name","type","latitude","longitude"],"properties":{"name":{"type":"string","minLength":2,"maxLength":255},"type":{"type":"string","enum":["azs","nb","gns","parking","office","other"]},"address":{"type":"string","maxLength":500},"latitude":{"type":"number","minimum":-90,"maximum":90},"longitude":{"type":"number","minimum":-180,"maximum":180},"geofenceRadiusM":{"type":"integer","minimum":10,"maximum":10000,"default":100},"reportIntervalMinutes":{"type":"integer","minimum":10,"maximum":1440,"default":120},"reportStartTime":{"type":"string","pattern":"^\\d{2}:\\d{2}$","example":"22:00"},"reportEndTime":{"type":"string","pattern":"^\\d{2}:\\d{2}$","example":"06:00"},"isActive":{"type":"boolean","default":true}}},"UpdateCORObjectRequest":{"type":"object","properties":{"name":{"type":"string","minLength":2,"maxLength":255},"type":{"type":"string","enum":["azs","nb","gns","parking","office","other"]},"address":{"type":"string","maxLength":500},"latitude":{"type":"number","minimum":-90,"maximum":90},"longitude":{"type":"number","minimum":-180,"maximum":180},"geofenceRadiusM":{"type":"integer","minimum":10,"maximum":10000},"reportIntervalMinutes":{"type":"integer","minimum":10,"maximum":1440},"reportStartTime":{"type":"string","pattern":"^\\d{2}:\\d{2}$"},"reportEndTime":{"type":"string","pattern":"^\\d{2}:\\d{2}$"},"isActive":{"type":"boolean"}}},"CORCheckpoint":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"object_id":{"type":"string","format":"uuid"},"name":{"type":"string"},"description":{"type":"string"},"latitude":{"type":"number","format":"double"},"longitude":{"type":"number","format":"double"},"radius_m":{"type":"integer","default":20},"sort_order":{"type":"integer","default":0},"is_active":{"type":"boolean","default":true},"created_at":{"type":"string","format":"date-time"},"updated_at":{"type":"string","format":"date-time"}}},"CreateCheckpointRequest":{"type":"object","required":["name","latitude","longitude"],"properties":{"name":{"type":"string","minLength":2,"maxLength":255},"description":{"type":"string","maxLength":1000},"latitude":{"type":"number","minimum":-90,"maximum":90},"longitude":{"type":"number","minimum":-180,"maximum":180},"radiusM":{"type":"integer","minimum":5,"maximum":1000,"default":20},"sortOrder":{"type":"integer","minimum":0,"default":0},"isActive":{"type":"boolean","default":true}}},"UpdateCheckpointRequest":{"type":"object","properties":{"name":{"type":"string","minLength":2,"maxLength":255},"description":{"type":"string","maxLength":1000},"latitude":{"type":"number","minimum":-90,"maximum":90},"longitude":{"type":"number","minimum":-180,"maximum":180},"radiusM":{"type":"integer","minimum":5,"maximum":1000},"sortOrder":{"type":"integer","minimum":0},"isActive":{"type":"boolean"}}},"BindUserRequest":{"type":"object","required":["userId","position"],"properties":{"userId":{"type":"string","format":"uuid"},"position":{"type":"string","minLength":2,"maxLength":100},"isPrimary":{"type":"boolean","default":true}}},"CORUserObject":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"user_id":{"type":"string","format":"uuid"},"object_id":{"type":"string","format":"uuid"},"position":{"type":"string"},"is_primary":{"type":"boolean"},"first_name":{"type":"string"},"last_name":{"type":"string"},"email":{"type":"string"},"phone":{"type":"string"},"role":{"type":"string"},"created_at":{"type":"string","format":"date-time"},"updated_at":{"type":"string","format":"date-time"}}},"CORPatrolLog":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"shift_id":{"type":"string","format":"uuid"},"checkpoint_id":{"type":"string","format":"uuid"},"user_id":{"type":"string","format":"uuid"},"photo_url":{"type":"string"},"latitude":{"type":"number"},"longitude":{"type":"number"},"is_within_radius":{"type":"boolean"},"created_at":{"type":"string","format":"date-time"}}},"CORPatrolStatus":{"type":"object","properties":{"checkpoints":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"name":{"type":"string"},"is_completed":{"type":"boolean"},"completed_at":{"type":"string","format":"date-time","nullable":true},"completed_photo_url":{"type":"string","nullable":true}}}},"completed":{"type":"integer"},"total":{"type":"integer"}}},"CORReport":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"shift_id":{"type":"string","format":"uuid"},"user_id":{"type":"string","format":"uuid"},"object_id":{"type":"string","format":"uuid"},"situation":{"type":"string","enum":["calm","suspicious","emergency"]},"description":{"type":"string"},"photo_urls":{"type":"array","items":{"type":"string"}},"latitude":{"type":"number","format":"double"},"longitude":{"type":"number","format":"double"},"is_late":{"type":"boolean"},"late_minutes":{"type":"integer"},"scheduled_at":{"type":"string","format":"date-time","nullable":true},"created_at":{"type":"string","format":"date-time"},"updated_at":{"type":"string","format":"date-time"},"first_name":{"type":"string"},"last_name":{"type":"string"},"object_name":{"type":"string"},"object_type":{"type":"string"}}},"SubmitReportRequest":{"type":"object","required":["shiftId","situation","latitude","longitude"],"properties":{"shiftId":{"type":"string","format":"uuid"},"situation":{"type":"string","enum":["calm","suspicious","emergency"]},"description":{"type":"string","maxLength":1000,"description":"Free-form text; may be empty or omitted."},"photoUrls":{"type":"array","items":{"type":"string","format":"uri"},"maxItems":5},"latitude":{"type":"number","minimum":-90,"maximum":90},"longitude":{"type":"number","minimum":-180,"maximum":180},"clientRequestId":{"type":"string","maxLength":64,"description":"Idempotency key generated by the client, one per user submission and reused by every delivery attempt (direct POST, offline-queue replay). When a report with this key already exists for the user, that report is returned instead of a second one being created. Optional — app builds predating the key omit it.\n"}}},"CORReportSchedule":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"shift_id":{"type":"string","format":"uuid"},"scheduled_at":{"type":"string","format":"date-time"},"status":{"type":"string","enum":["pending","reminded_1","reminded_2","overdue","completed"]},"report_id":{"type":"string","format":"uuid","nullable":true},"reminder_1_sent_at":{"type":"string","format":"date-time","nullable":true},"reminder_2_sent_at":{"type":"string","format":"date-time","nullable":true},"overdue_sent_at":{"type":"string","format":"date-time","nullable":true},"created_at":{"type":"string","format":"date-time"},"updated_at":{"type":"string","format":"date-time"},"date_label":{"type":"string","description":"Section label computed server-side in Bishkek time (e.g. \"Сегодня\", \"Вчера\", \"9 апреля\"). Only past slots are returned.","example":"Сегодня"}}},"CORShift":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"user_id":{"type":"string","format":"uuid"},"object_id":{"type":"string","format":"uuid"},"started_at":{"type":"string","format":"date-time"},"ended_at":{"type":"string","format":"date-time","nullable":true},"start_latitude":{"type":"number","format":"double"},"start_longitude":{"type":"number","format":"double"},"start_photo_url":{"type":"string"},"is_outside_geofence":{"type":"boolean"},"device_id":{"type":"string"},"status":{"type":"string","enum":["active","completed","abandoned"]},"created_at":{"type":"string","format":"date-time"},"updated_at":{"type":"string","format":"date-time"},"object_name":{"type":"string"},"object_type":{"type":"string"},"first_name":{"type":"string"},"last_name":{"type":"string"},"report_count":{"type":"integer"},"late_count":{"type":"integer"}}},"StartShiftRequest":{"type":"object","required":["objectId","latitude","longitude","photoUrl","deviceId"],"properties":{"objectId":{"type":"string","format":"uuid"},"latitude":{"type":"number","minimum":-90,"maximum":90},"longitude":{"type":"number","minimum":-180,"maximum":180},"photoUrl":{"type":"string","format":"uri"},"deviceId":{"type":"string","maxLength":255}}},"CORVehicle":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"name":{"type":"string"},"plate_number":{"type":"string"},"gps_tracker_id":{"type":"string","nullable":true},"vehicle_type":{"type":"string","enum":["fuel_truck","service","other"]},"max_speed_kmh":{"type":"integer"},"max_stop_minutes":{"type":"integer"},"fuel_tank_capacity_l":{"type":"number","nullable":true},"is_active":{"type":"boolean"},"created_at":{"type":"string","format":"date-time"},"updated_at":{"type":"string","format":"date-time"}}},"CORVehicleEvent":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"vehicle_id":{"type":"string","format":"uuid"},"event_type":{"type":"string","enum":["overspeed","long_stop","zone_violation","fuel_drain","fuel_drop","route_deviation","no_movement","signal_lost","signal_restored"]},"latitude":{"type":"number","nullable":true},"longitude":{"type":"number","nullable":true},"speed_kmh":{"type":"number","nullable":true},"fuel_level_l":{"type":"number","nullable":true},"details":{"type":"object"},"is_acknowledged":{"type":"boolean"},"acknowledged_by":{"type":"string","format":"uuid","nullable":true},"acknowledged_at":{"type":"string","format":"date-time","nullable":true},"created_at":{"type":"string","format":"date-time"},"vehicle_name":{"type":"string"},"plate_number":{"type":"string"}}},"CORVehicleZone":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"name":{"type":"string"},"zone_type":{"type":"string","enum":["allowed","forbidden"]},"polygon":{"type":"object","description":"GeoJSON polygon"},"is_active":{"type":"boolean"},"created_at":{"type":"string","format":"date-time"}}},"WialonUnitPosition":{"type":"object","nullable":true,"properties":{"x":{"type":"number","description":"Longitude"},"y":{"type":"number","description":"Latitude"},"z":{"type":"number","description":"Altitude (metres)"},"s":{"type":"number","description":"Speed (km/h)"},"c":{"type":"number","description":"Course (degrees)"},"t":{"type":"integer","description":"Unix timestamp of position"}}},"WialonUnit":{"type":"object","properties":{"id":{"type":"integer","description":"Wialon unit ID"},"nm":{"type":"string","description":"Unit name"},"pos":{"$ref":"#/components/schemas/WialonUnitPosition"},"lmsg":{"type":"object","nullable":true,"properties":{"t":{"type":"integer","description":"Last message timestamp (Unix)"},"f":{"type":"integer","description":"Flags"}}}}},"WialonTemplate":{"type":"object","properties":{"id":{"type":"integer"},"n":{"type":"string","description":"Template name"},"ct":{"type":"string","description":"Created time"}}},"WialonResource":{"type":"object","properties":{"id":{"type":"integer"},"nm":{"type":"string","description":"Resource name"},"rep_templ":{"type":"object","additionalProperties":{"$ref":"#/components/schemas/WialonTemplate"},"description":"Report templates keyed by template ID"}}},"WialonReportTable":{"type":"object","properties":{"name":{"type":"string"},"header":{"type":"array","items":{"type":"string"}},"rows":{"type":"integer","description":"Number of rows in the table"},"level":{"type":"integer"},"grouping":{"type":"string"},"cols":{"type":"integer"}}},"WialonReportResult":{"type":"object","properties":{"tables":{"type":"array","items":{"$ref":"#/components/schemas/WialonReportTable"}}}},"WialonReportRowCell":{"oneOf":[{"type":"string"},{"type":"object","properties":{"t":{"type":"string","description":"Display text"},"v":{"type":"number","description":"Numeric value"},"y":{"type":"number","description":"Latitude (for geo cells)"},"x":{"type":"number","description":"Longitude (for geo cells)"}}}]},"WialonReportRow":{"type":"object","properties":{"n":{"type":"integer","description":"Row index"},"c":{"type":"array","items":{"$ref":"#/components/schemas/WialonReportRowCell"}}}},"WialonGeofence":{"type":"object","properties":{"id":{"type":"integer","description":"Wialon geofence ID"},"name":{"type":"string","description":"Geofence name"},"description":{"type":"string","description":"Geofence description"},"type":{"type":"string","enum":["Круг","Многоугольник","Линия"],"description":"Geometry type"},"radius":{"type":"integer","nullable":true,"description":"Radius in metres (circles only)"},"center":{"type":"string","description":"First point as 'lat, lng' string","example":"42.87000, 74.59000"},"pointsCount":{"type":"integer","description":"Number of vertices in the geofence polygon/line"},"resourceName":{"type":"string","description":"Name of the Wialon resource that owns this geofence"}}},"WialonStatus":{"type":"object","properties":{"connected":{"type":"boolean","description":"Whether an active Wialon session exists"},"username":{"type":"string","nullable":true,"description":"Username of the connected session"},"expiresAt":{"type":"integer","nullable":true,"description":"Session expiry as Unix timestamp (milliseconds)"},"isPolling":{"type":"boolean","description":"Whether the 5-second real-time polling loop is active"}}}},"parameters":{"PageParam":{"name":"page","in":"query","description":"Page number for pagination","required":false,"schema":{"type":"integer","minimum":1,"default":1}},"LimitParam":{"name":"limit","in":"query","description":"Number of items per page","required":false,"schema":{"type":"integer","minimum":1,"maximum":100,"default":20}},"SortParam":{"name":"sort","in":"query","description":"Sort field and direction (e.g., 'createdAt:desc')","required":false,"schema":{"type":"string","pattern":"^[a-zA-Z_][a-zA-Z0-9_]*:(asc|desc)$"}},"User":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"email":{"type":"string","format":"email"},"first_name":{"type":"string"},"last_name":{"type":"string"},"phone":{"type":"string","nullable":true},"role":{"type":"string","enum":["client","dispatcher","brigade_member","admin"]},"status":{"type":"string","enum":["active","inactive","suspended"]},"emailVerified":{"type":"boolean"},"phoneVerified":{"type":"boolean"},"avatar_url":{"type":"string","format":"uri","description":"URL to user's profile picture","nullable":true},"createdAt":{"type":"string","format":"date-time"},"updatedAt":{"type":"string","format":"date-time"}}},"Brigade":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"name":{"type":"string"},"description":{"type":"string","nullable":true},"status":{"type":"string","enum":["active","inactive","maintenance"]},"currentLocation":{"type":"object","nullable":true,"properties":{"lat":{"type":"number","format":"double"},"lng":{"type":"number","format":"double"}}},"zoneId":{"type":"string","format":"uuid","nullable":true},"createdAt":{"type":"string","format":"date-time"},"updatedAt":{"type":"string","format":"date-time"}}},"PaginatedResponse":{"type":"object","properties":{"success":{"type":"boolean"},"pagination":{"type":"object","properties":{"page":{"type":"integer","minimum":1},"limit":{"type":"integer","minimum":1,"maximum":100},"total":{"type":"integer","minimum":0},"pages":{"type":"integer","minimum":0}}}}}},"responses":{"ValidationError":{"description":"Validation error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string","example":"Validation failed"},"details":{"type":"array","items":{"type":"object","properties":{"field":{"type":"string"},"message":{"type":"string"}}}}}}}}}}},"UnauthorizedError":{"description":"Authentication required","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string","example":"Authentication required"}}}}}}}},"NotFoundError":{"description":"Resource not found","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string","example":"Resource not found"}}}}}}}},"InternalServerError":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string","example":"Internal server error"}}}}}}}},"ForbiddenError":{"description":"Forbidden access","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string","example":"Forbidden access"}}}}}}}},"BadRequestError":{"description":"Bad request","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string","example":"Bad request"}}}}}}}}}},"tags":[{"name":"Health","description":"System health and monitoring"},{"name":"Audit Logs","description":"System audit logs and monitoring"},{"name":"Authentication","description":"User authentication and authorization"},{"name":"Brigades","description":"Brigade management and operations"},{"name":"Calls","description":"Call management and operations"},{"name":"Cars","description":"Car management and operations"},{"name":"Chat","description":"Real-time messaging between users"},{"name":"Client Addresses","description":"Client address management"},{"name":"Connected Objects","description":"Connected object management"},{"name":"Corporate Management","description":"Corporate management and operations"},{"name":"Device Tokens","description":"Device token management for push notifications"},{"name":"Enhanced Profile","description":"Enhanced profile management and operations"},{"name":"Family Management","description":"Family management and operations"},{"name":"Invoices","description":"Invoice management and operations"},{"name":"Notifications","description":"User notification management and preferences"},{"name":"OTP","description":"Email and phone verification management and operations"},{"name":"Quotas","description":"Quota management and tracking"},{"name":"Reports","description":"Analytics and reporting"},{"name":"Services","description":"Addon service management"},{"name":"Support Chat","description":"Support chat management and operations"},{"name":"Tariff Plans","description":"Quota-based subscription plan management"},{"name":"Upload","description":"File upload and management"},{"name":"User Services","description":"User service purchases"},{"name":"User Subscriptions","description":"User subscription operations"},{"name":"Users","description":"User management operations"},{"name":"Work Schedule","description":"Employee work schedule tracking and management"},{"name":"Zones","description":"Geographic zone management and operations"},{"name":"App Versions","description":"Mobile app version management"},{"name":"Geocoding","description":"Address geocoding via Google Maps API"},{"name":"Payments","description":"NPay платежная система - оплата подписок и услуг"},{"name":"Ratings","description":"Call rating and feedback management"},{"name":"Routing","description":"OSRM-based road routing for map directions"},{"name":"Service Applications","description":"Заявки на услуги с договорной ценой"},{"name":"COR Events","description":"COR event log / audit trail"},{"name":"COR Objects","description":"COR (Central Operations Room) object management"},{"name":"COR Reports","description":"COR situation report management"},{"name":"COR Shifts","description":"COR shift management for operators"},{"name":"COR Vehicles","description":"COR vehicle management, events, and zones"},{"name":"COR Wialon","description":"Wialon GPS tracking platform integration for COR dashboard"}],"paths":{"/api/app-versions":{"get":{"tags":["App Versions"],"summary":"Get app versions (public)","description":"Returns latest and minimum versions for all mobile apps per platform. No authentication required — called by mobile apps on launch.","responses":{"200":{"description":"Version info grouped by app and platform","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"object","properties":{"clientApp":{"$ref":"#/components/schemas/AppPlatformVersions"},"brigadaApp":{"$ref":"#/components/schemas/AppPlatformVersions"}}}}}}}}}}},"/api/app-versions/all":{"get":{"tags":["App Versions"],"summary":"Get all version records (admin)","description":"Returns raw app_versions records for the admin settings page.","security":[{"bearerAuth":[]}],"responses":{"200":{"description":"Array of version records","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"array","items":{"$ref":"#/components/schemas/AppVersionRecord"}}}}}}}}}},"/api/app-versions/{appKey}":{"get":{"tags":["App Versions"],"summary":"Get version info for a specific app (public)","description":"Returns latest and minimum versions per platform for a single app key. No auth required — called on app launch before login.","parameters":[{"in":"path","name":"appKey","required":true,"schema":{"type":"string","enum":["client","brigada","orc"]}}],"responses":{"200":{"description":"Version info for the requested app keyed by platform","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/AppPlatformVersions"}}}}}},"400":{"description":"Unknown appKey"}}}},"/api/app-versions/{id}":{"put":{"tags":["App Versions"],"summary":"Update app version (admin)","description":"Update latest/minimum version for a specific app/platform.","security":[{"bearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateAppVersionRequest"}}}},"responses":{"200":{"description":"Updated version record"}}}},"/api/audit-logs":{"get":{"summary":"Get audit logs","description":"Get paginated list of audit logs with filtering (admins only)","tags":["Audit Logs"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"query","name":"page","schema":{"type":"integer","minimum":1,"default":1},"description":"Page number for pagination"},{"in":"query","name":"limit","schema":{"type":"integer","minimum":1,"maximum":100,"default":50},"description":"Number of items per page"},{"in":"query","name":"userId","schema":{"type":"string","format":"uuid"},"description":"Filter by user ID"},{"in":"query","name":"action","schema":{"type":"string"},"description":"Filter by action type"},{"in":"query","name":"resource","schema":{"type":"string"},"description":"Filter by resource type"},{"in":"query","name":"resourceId","schema":{"type":"string","format":"uuid"},"description":"Filter by specific resource ID"},{"in":"query","name":"startDate","schema":{"type":"string","format":"date-time"},"description":"Filter logs after this date"},{"in":"query","name":"endDate","schema":{"type":"string","format":"date-time"},"description":"Filter logs before this date"},{"in":"query","name":"ipAddress","schema":{"type":"string","format":"ipv4"},"description":"Filter by IP address"},{"in":"query","name":"search","schema":{"type":"string"},"description":"Search in action, resource, or user details"}],"responses":{"200":{"description":"Audit logs retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/PaginatedAuditLogs"}}}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"Insufficient permissions (admin required)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForbiddenError"}}}}}}},"/api/audit-logs/security":{"get":{"summary":"Get security events","description":"Get paginated list of security-related audit logs (admins only)","tags":["Audit Logs"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"query","name":"page","schema":{"type":"integer","minimum":1,"default":1},"description":"Page number for pagination"},{"in":"query","name":"limit","schema":{"type":"integer","minimum":1,"maximum":100,"default":50},"description":"Number of items per page"},{"in":"query","name":"startDate","schema":{"type":"string","format":"date-time"},"description":"Filter logs after this date"},{"in":"query","name":"endDate","schema":{"type":"string","format":"date-time"},"description":"Filter logs before this date"},{"in":"query","name":"ipAddress","schema":{"type":"string","format":"ipv4"},"description":"Filter by IP address"}],"responses":{"200":{"description":"Security events retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/PaginatedAuditLogs"}}}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"Insufficient permissions (admin required)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForbiddenError"}}}}}}},"/api/audit-logs/export":{"get":{"summary":"Export audit logs to CSV","description":"Export audit logs to CSV format (admins only)","tags":["Audit Logs"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"query","name":"userId","schema":{"type":"string","format":"uuid"},"description":"Filter by user ID"},{"in":"query","name":"action","schema":{"type":"string"},"description":"Filter by action type"},{"in":"query","name":"resource","schema":{"type":"string"},"description":"Filter by resource type"},{"in":"query","name":"startDate","schema":{"type":"string","format":"date-time"},"description":"Filter logs after this date"},{"in":"query","name":"endDate","schema":{"type":"string","format":"date-time"},"description":"Filter logs before this date"}],"responses":{"200":{"description":"CSV file with audit logs","content":{"text/csv":{"schema":{"type":"string","format":"binary"}}},"headers":{"Content-Disposition":{"description":"Attachment filename","schema":{"type":"string","example":"attachment; filename=\"audit-logs-2023-11-06.csv\""}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"Insufficient permissions (admin required)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForbiddenError"}}}}}}},"/api/audit-logs/user/{userId}":{"get":{"summary":"Get audit logs for specific user","description":"Get paginated list of audit logs for a specific user (admins only)","tags":["Audit Logs"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"userId","required":true,"schema":{"type":"string","format":"uuid"},"description":"User ID"},{"in":"query","name":"page","schema":{"type":"integer","minimum":1,"default":1},"description":"Page number for pagination"},{"in":"query","name":"limit","schema":{"type":"integer","minimum":1,"maximum":100,"default":50},"description":"Number of items per page"},{"in":"query","name":"action","schema":{"type":"string"},"description":"Filter by action type"},{"in":"query","name":"resource","schema":{"type":"string"},"description":"Filter by resource type"},{"in":"query","name":"startDate","schema":{"type":"string","format":"date-time"},"description":"Filter logs after this date"},{"in":"query","name":"endDate","schema":{"type":"string","format":"date-time"},"description":"Filter logs before this date"}],"responses":{"200":{"description":"User audit logs retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/PaginatedAuditLogs"}}}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"Insufficient permissions (admin required)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForbiddenError"}}}}}}},"/api/audit-logs/resource/{resource}/{resourceId}":{"get":{"summary":"Get audit logs for specific resource","description":"Get paginated list of audit logs for a specific resource (admins only)","tags":["Audit Logs"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"resource","required":true,"schema":{"type":"string"},"description":"Resource type (e.g., 'users', 'calls', 'brigades')"},{"in":"path","name":"resourceId","required":true,"schema":{"type":"string","format":"uuid"},"description":"Resource ID"},{"in":"query","name":"page","schema":{"type":"integer","minimum":1,"default":1},"description":"Page number for pagination"},{"in":"query","name":"limit","schema":{"type":"integer","minimum":1,"maximum":100,"default":50},"description":"Number of items per page"}],"responses":{"200":{"description":"Resource audit logs retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/PaginatedAuditLogs"}}}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"Insufficient permissions (admin required)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForbiddenError"}}}}}}},"/api/audit-logs/{id}":{"get":{"summary":"Get audit log by ID","description":"Get a specific audit log entry by its ID (admins only)","tags":["Audit Logs"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"},"description":"Audit log ID"}],"responses":{"200":{"description":"Audit log retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/AuditLogWithUser"}}}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"Insufficient permissions (admin required)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForbiddenError"}}}},"404":{"description":"Audit log not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/NotFoundError"}}}}}}},"/api/audit-logs/cleanup":{"post":{"summary":"Clean up old audit logs","description":"Delete audit logs older than specified retention period (admins only)","tags":["Audit Logs"],"security":[{"BearerAuth":[]}],"requestBody":{"required":false,"content":{"application/json":{"schema":{"type":"object","properties":{"retentionDays":{"type":"integer","minimum":30,"maximum":3650,"default":365,"description":"Number of days to retain audit logs","example":365}}}}}},"responses":{"200":{"description":"Cleanup completed successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"object","properties":{"deletedCount":{"type":"integer","description":"Number of audit logs deleted","example":1250},"retentionDays":{"type":"integer","description":"Retention period used","example":365}}},"message":{"type":"string","example":"Successfully deleted 1250 old audit logs"}}}}}},"400":{"description":"Invalid retention period","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string","example":"Retention days must be between 30 and 3650"}}}}}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"Insufficient permissions (admin required)","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string","example":"Admin access required"}}}}}}}}}}},"/api/auth/login":{"post":{"tags":["Authentication"],"summary":"User login","description":"Authenticate a user with a password and an account identifier — either an email address or a phone number, both posted under the `email` key. A phone number is resolved on its full digits first, then on the trailing nine, so \"+996555123456\" and \"0555123456\" reach the same account. If the trailing nine digits match more than one active account and the full number matches none of them exactly, the request is refused with 409 rather than signing the caller into an arbitrary one.\n","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/LoginRequest"},"example":{"email":"user@example.com","password":"password123"}}}},"responses":{"200":{"description":"Login successful","content":{"application/json":{"schema":{"$ref":"#/components/schemas/LoginResponse"},"example":{"success":true,"data":{"accessToken":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...","refreshToken":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...","user":{"id":"123e4567-e89b-12d3-a456-426614174000","email":"user@example.com","first_name":"John","last_name":"Doe","role":"client"},"expiresIn":86400}}}}},"400":{"$ref":"#/components/responses/ValidationError"},"401":{"description":"Invalid credentials","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"409":{"description":"PHONE_IDENTIFIER_AMBIGUOUS — the trailing nine digits of the phone number identify more than one active account and no account matches the full number. Sign in by email instead.\n","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"code":{"type":"string","example":"PHONE_IDENTIFIER_AMBIGUOUS"},"message":{"type":"string"}}}}}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/auth/register":{"post":{"tags":["Authentication"],"summary":"User registration","description":"Register a new user account. `email` and `phone` are each optional but at least one must be present — it identifies the account at login and receives the one-time code. Omitting both returns 400.\nAlways creates a `client`. A `role` field in the body is accepted and silently discarded — the released mobile apps send `role: \"client\"`, so rejecting the key would break registration for them, but the value is never read. This endpoint is unauthenticated; granting a role belongs to the admin-only `/users` path.\n","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["password","first_name","last_name"],"anyOf":[{"required":["email"]},{"required":["phone"]}],"properties":{"email":{"type":"string","format":"email","description":"Optional when a phone number is supplied."},"password":{"type":"string","minLength":6},"first_name":{"type":"string"},"last_name":{"type":"string"},"phone":{"type":"string","pattern":"^\\\\+?[1-9]\\\\d{1,14}$","description":"Optional when an email address is supplied."},"otpCode":{"type":"string","minLength":6,"maxLength":6,"pattern":"^[0-9]+$","description":"The registration code already verified for `phone`. Supply it to have the number stored as verified, so the client does not prompt the user to confirm a number they just confirmed. Optional — omitting it registers the number as unverified. An expired or mismatched code does not fail the registration.\n"}}},"example":{"email":"newuser@example.com","password":"securepassword123","first_name":"Jane","last_name":"Smith","phone":"+1234567890"}}}},"responses":{"201":{"description":"User registered successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/User"}}}}}},"400":{"$ref":"#/components/responses/ValidationError"},"409":{"description":"User already exists, or the phone number collides with an active account on its trailing nine digits (which would lock both accounts out of phone login).\n","content":{"application/json":{"schema":{"type":"object","properties":{"message":{"type":"string","example":"User with this email already exists"}}}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/auth/register-legal":{"post":{"tags":["Authentication"],"summary":"Legal entity owner registration","description":"Register a new legal entity (company) with owner account. Creates user\naccount, legal entity, and binds them together with corporate employee\nrelationship.\n\nOptional fields accept an empty string and treat it as omitted\n(`registrationNumber`, `companyPhone`, `website`, `billingAddress`,\n`industry`, `description`). `employeeCount` likewise treats `0` as\n\"not stated\" rather than measuring it against the minimum of 1, so a\nclient that posts a parsed blank input is not refused.\n\nA company that previously closed its account re-registers normally: the\nsoft-deleted legal entity holding that `taxId` is reactivated with the\nsubmitted details, and the owner's membership is restored. An entity\nthat is still live answers 409 `LEGAL_ENTITY_ALREADY_EXISTS`, and a\nphone already held by a live account answers 409 `USER_EXISTS` —\nmatched on the trailing nine digits, so another spelling of the same\nnumber is recognised as the same person.\n","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["email","password","first_name","last_name","companyName","legalName","taxId","companyEmail","legalAddress"],"properties":{"email":{"type":"string","format":"email","description":"Owner's email address"},"phone":{"type":"string","pattern":"^\\\\+?[1-9]\\\\d{1,14}$","description":"Owner's phone number"},"password":{"type":"string","minLength":6,"description":"Owner's password"},"first_name":{"type":"string","minLength":2,"maxLength":50,"description":"Owner's first name"},"last_name":{"type":"string","minLength":2,"maxLength":50,"description":"Owner's last name"},"companyName":{"type":"string","maxLength":200,"description":"Company trade name"},"legalName":{"type":"string","maxLength":200,"description":"Legal company name"},"taxId":{"type":"string","maxLength":50,"description":"Tax identification number (ИНН)"},"registrationNumber":{"type":"string","maxLength":100,"description":"Company registration number (ОГРН)"},"companyEmail":{"type":"string","format":"email","description":"Company contact email"},"companyPhone":{"type":"string","maxLength":20,"description":"Company contact phone"},"website":{"type":"string","format":"uri","description":"Company website URL"},"legalAddress":{"type":"string","description":"Legal address of the company"},"billingAddress":{"type":"string","description":"Billing address (if different from legal)"},"industry":{"type":"string","maxLength":100,"description":"Industry sector"},"employeeCount":{"type":"integer","minimum":1,"description":"Number of employees"},"description":{"type":"string","description":"Company description"}}},"example":{"email":"owner@company.com","phone":"+79991234567","password":"securepass123","first_name":"Иван","last_name":"Петров","companyName":"ООО Безопасность","legalName":"Общество с ограниченной ответственностью Безопасность","taxId":"7707123456","registrationNumber":"1027700123456","companyEmail":"info@company.com","companyPhone":"+74951234567","website":"https://company.com","legalAddress":"г. Москва, ул. Ленина, д. 1","billingAddress":"г. Москва, ул. Ленина, д. 1","industry":"Охранные услуги","employeeCount":50,"description":"Охранная компания с 10-летним опытом"}}}},"responses":{"201":{"description":"Legal entity and owner registered successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"user":{"$ref":"#/components/schemas/User"},"legalEntityId":{"type":"string","format":"uuid","description":"Created legal entity ID"},"accessToken":{"type":"string","description":"JWT access token"},"refreshToken":{"type":"string","description":"JWT refresh token"},"message":{"type":"string","example":"Юридическое лицо и владелец успешно зарегистрированы"}}}}}},"400":{"description":"Validation error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Неверный формат email"},"errors":{"type":"array","items":{"type":"object","properties":{"field":{"type":"string"},"message":{"type":"string"}}}}}}}}},"409":{"description":"User or legal entity already exists","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"string","enum":["USER_EXISTS","LEGAL_ENTITY_ALREADY_EXISTS"]},"message":{"type":"string"}}}}}},"422":{"description":"Failed to create legal entity or owner","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"string","enum":["LEGAL_ENTITY_NOT_CREATED","LEGAL_ENTITY_OWNER_CREATION_FAILED"]},"message":{"type":"string"}}}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/auth/refresh":{"post":{"tags":["Authentication"],"summary":"Refresh access token","description":"Get a new access token using refresh token","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["refreshToken"],"properties":{"refreshToken":{"type":"string"}}},"example":{"refreshToken":"refresh_token_here"}}}},"responses":{"200":{"description":"Token refreshed successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"object","properties":{"accessToken":{"type":"string"},"refreshToken":{"type":"string"}}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/auth/logout":{"post":{"tags":["Authentication"],"summary":"User logout","description":"Logout user and invalidate tokens","security":[{"BearerAuth":[]}],"responses":{"200":{"description":"Logout successful","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Logged out successfully"}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/auth/me":{"get":{"tags":["Authentication"],"summary":"Get current user profile","description":"Retrieve the profile of the currently authenticated user. If user is associated with a legal entity, legalEntityId will be included.","security":[{"BearerAuth":[]}],"responses":{"200":{"description":"Profile retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"email":{"type":"string","format":"email"},"phone":{"type":"string"},"first_name":{"type":"string"},"last_name":{"type":"string"},"role":{"type":"string","enum":["client","dispatcher","admin","brigade_member"]},"status":{"type":"string","enum":["active","inactive","suspended"]},"emailVerified":{"type":"boolean"},"phoneVerified":{"type":"boolean"},"avatar_url":{"type":"string"},"legalEntityId":{"type":"string","format":"uuid","description":"Legal entity ID if user is associated with a company (only present for corporate users)"},"createdAt":{"type":"string","format":"date-time"},"updatedAt":{"type":"string","format":"date-time"}}},"example":{"id":"123e4567-e89b-12d3-a456-426614174000","email":"owner@company.com","phone":"+79991234567","first_name":"Иван","last_name":"Петров","role":"client","status":"active","emailVerified":false,"phoneVerified":false,"legalEntityId":"987e6543-e21b-12d3-a456-426614174000","createdAt":"2025-12-15T08:00:00.000Z","updatedAt":"2025-12-15T08:00:00.000Z"}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/auth/change-password":{"post":{"tags":["Authentication"],"summary":"Change user password","description":"Change the password for the currently authenticated user","security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["currentPassword","newPassword"],"properties":{"currentPassword":{"type":"string","description":"Current password"},"newPassword":{"type":"string","minLength":8,"description":"New password (minimum 8 characters)"}}},"example":{"currentPassword":"oldpassword123","newPassword":"newpassword456"}}}},"responses":{"200":{"description":"Password changed successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Пароль успешно изменен"}}}}}},"400":{"description":"Validation error or incorrect current password","content":{"application/json":{"schema":{"type":"object","properties":{"message":{"type":"string","example":"Текущий пароль неверен"}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/auth/admin/reset-password":{"post":{"tags":["Authentication"],"summary":"Admin reset user password","description":"Reset password for a brigade member (admin/dispatcher only)","security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["email","newPassword"],"properties":{"email":{"type":"string","format":"email","description":"Email of the user whose password to reset"},"newPassword":{"type":"string","minLength":8,"description":"New password (minimum 8 characters)"}}},"example":{"email":"brigade.leader@example.com","newPassword":"newpassword123"}}}},"responses":{"200":{"description":"Password reset successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Пароль пользователя успешно сброшен. Пользователь должен войти с новым паролем"}}}}}},"400":{"description":"Validation error","content":{"application/json":{"schema":{"type":"object","properties":{"message":{"type":"string","example":"Email is required"}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Access denied - only admin/dispatcher can reset passwords","content":{"application/json":{"schema":{"type":"object","properties":{"message":{"type":"string","example":"Доступ запрещен"}}}}}},"404":{"description":"User not found","content":{"application/json":{"schema":{"type":"object","properties":{"message":{"type":"string","example":"Пользователь не найден"}}}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/auth/forgot-password":{"post":{"tags":["Authentication"],"summary":"Forgot password - Send OTP","description":"Send a one-time code for password reset. The identifier may be an email address or a phone number, both posted under the `email` key.\nThe code is delivered to the contact stored on the resolved account, not to the identifier as posted. A phone is matched on its trailing nine subscriber digits, so a near-miss such as `+1555123456` resolves the account held as `+996555123456` and the SMS goes to the stored number.\n","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["email"],"properties":{"email":{"type":"string","description":"Account identifier - email address or phone number","example":"user@example.com"}}},"example":{"email":"user@example.com"}}}},"responses":{"200":{"description":"Always returned, with an identical body, whether or not an account matched and whether or not delivery succeeded — the endpoint must not reveal which accounts exist. Delivery failures are logged server-side.\n","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Если пользователь с такими данными существует, код подтверждения будет отправлен"}}}}}},"400":{"description":"Validation error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string","example":"Validation failed"},"details":{"type":"array","items":{"type":"object","properties":{"field":{"type":"string","example":"email"},"message":{"type":"string","example":"Please provide a valid email address"}}}}}}}}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/auth/reset-password":{"post":{"tags":["Authentication"],"summary":"Reset password with OTP","description":"Validate OTP code and set new password","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["email","otpCode","newPassword"],"properties":{"email":{"type":"string","format":"email","description":"User's email address","example":"user@example.com"},"otpCode":{"type":"string","pattern":"^[0-9]{6}$","description":"6-digit OTP code received via email","example":"123456"},"newPassword":{"type":"string","minLength":6,"maxLength":128,"description":"New password for the account","example":"newSecurePassword123"}}},"example":{"email":"user@example.com","otpCode":"123456","newPassword":"newSecurePassword123"}}}},"responses":{"200":{"description":"Password reset successful","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Пароль успешно изменен. Теперь вы можете войти в систему с новым паролем."}}}}}},"400":{"description":"Validation error or invalid OTP","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string","example":"Неверный или истекший код подтверждения"}}}}}}}},"409":{"description":"The phone number is registered to more than one account (the last nine digits match several users), so there is no safe way to choose whose password is being reset. Sign in by email or contact support.\n","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string","example":"Этот номер телефона указан у нескольких пользователей. Войдите по email или обратитесь к администратору."}}}}}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/auth/revoke":{"post":{"tags":["Authentication"],"summary":"Revoke specific token","description":"Revoke the current access token (extracted from Authorization header)","security":[{"BearerAuth":[]}],"responses":{"200":{"description":"Token revoked successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Token revoked successfully"}}}}}},"400":{"description":"No token provided","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","example":"No token provided"}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/auth/revoke-all":{"post":{"tags":["Authentication"],"summary":"Revoke all user tokens","description":"Revoke all tokens for the currently authenticated user (security endpoint for logging out all sessions)","security":[{"BearerAuth":[]}],"responses":{"200":{"description":"All tokens revoked successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"All tokens revoked successfully"}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/brigades/info":{"get":{"tags":["Brigades"],"summary":"Get brigade info for authenticated member","description":"Retrieve full brigade information for the authenticated brigade member. Only brigade members can access this endpoint and it returns their own brigade details including all members and car information. If the user is not assigned to any brigade, responds 200 with data: null.","security":[{"BearerAuth":[]}],"responses":{"200":{"description":"Brigade info retrieved successfully (data is null when the user has no brigade)","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"nullable":true,"description":"Brigade details, or null if the user is not assigned to any brigade","allOf":[{"$ref":"#/components/schemas/Brigade"},{"type":"object","properties":{"members":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"userId":{"type":"string","format":"uuid"},"role":{"type":"string","enum":["leader","member"]},"joinedAt":{"type":"string","format":"date-time"},"user":{"type":"object","properties":{"first_name":{"type":"string"},"last_name":{"type":"string"},"email":{"type":"string"},"phone":{"type":"string"}}}}}},"car":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"licensePlate":{"type":"string"},"model":{"type":"string"},"year":{"type":"integer"},"color":{"type":"string"},"photoUrl":{"type":"string"},"status":{"type":"string"},"gpsDeviceId":{"type":"string"}}}}}]}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Access denied - only brigade members can access this endpoint","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","example":"Only brigade members can access brigade info"}}}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/brigades":{"get":{"tags":["Brigades"],"summary":"Get all brigades","description":"Retrieve a paginated list of brigades with optional filtering","security":[{"BearerAuth":[]}],"parameters":[{"$ref":"#/components/parameters/PageParam"},{"$ref":"#/components/parameters/LimitParam"},{"$ref":"#/components/parameters/SortParam"},{"name":"status","in":"query","description":"Filter by brigade status","schema":{"type":"string","enum":["active","inactive","maintenance"]}},{"name":"zoneId","in":"query","description":"Filter by zone ID","schema":{"type":"string","format":"uuid"}},{"name":"search","in":"query","description":"Search by brigade name","schema":{"type":"string"}}],"responses":{"200":{"description":"Brigades retrieved successfully","content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/PaginatedResponse"},{"type":"object","properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/Brigade"}}}}]}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"500":{"$ref":"#/components/responses/InternalServerError"}}},"post":{"tags":["Brigades"],"summary":"Create a new brigade","description":"Create a new brigade (Admin/Dispatcher only)","security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["name"],"properties":{"name":{"type":"string","maxLength":100},"description":{"type":"string","maxLength":500},"zoneId":{"type":"string","format":"uuid"}}},"example":{"name":"Alpha Brigade","description":"Primary response team for downtown area","zoneId":"123e4567-e89b-12d3-a456-426614174000"}}}},"responses":{"201":{"description":"Brigade created successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/Brigade"}}}}}},"400":{"$ref":"#/components/responses/ValidationError"},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Insufficient permissions"},"409":{"description":"Brigade name already exists"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/brigades/{id}":{"get":{"tags":["Brigades"],"summary":"Get brigade by ID","description":"Retrieve a specific brigade by its ID with member details","security":[{"BearerAuth":[]}],"parameters":[{"name":"id","in":"path","required":true,"description":"Brigade ID","schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Brigade retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"allOf":[{"$ref":"#/components/schemas/Brigade"},{"type":"object","properties":{"members":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"userId":{"type":"string","format":"uuid"},"role":{"type":"string","enum":["leader","member"]},"joinedAt":{"type":"string","format":"date-time"},"user":{"type":"object","properties":{"first_name":{"type":"string"},"last_name":{"type":"string"},"email":{"type":"string"},"phone":{"type":"string"}}}}}}}}]}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"404":{"$ref":"#/components/responses/NotFoundError"},"500":{"$ref":"#/components/responses/InternalServerError"}}},"put":{"tags":["Brigades"],"summary":"Update brigade","description":"Update an existing brigade (Admin/Dispatcher only)","security":[{"BearerAuth":[]}],"parameters":[{"name":"id","in":"path","required":true,"description":"Brigade ID","schema":{"type":"string","format":"uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string","maxLength":100},"description":{"type":"string","maxLength":500},"status":{"type":"string","enum":["active","inactive","maintenance"]},"zoneId":{"type":"string","format":"uuid"}}},"example":{"name":"Alpha Brigade Updated","description":"Updated description","status":"active"}}}},"responses":{"200":{"description":"Brigade updated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/Brigade"}}}}}},"400":{"$ref":"#/components/responses/ValidationError"},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Insufficient permissions"},"404":{"$ref":"#/components/responses/NotFoundError"},"500":{"$ref":"#/components/responses/InternalServerError"}}},"delete":{"tags":["Brigades"],"summary":"Delete brigade","description":"Delete a brigade (Admin only)","security":[{"BearerAuth":[]}],"parameters":[{"name":"id","in":"path","required":true,"description":"Brigade ID","schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Brigade deleted successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Brigade deleted successfully"}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Insufficient permissions"},"404":{"$ref":"#/components/responses/NotFoundError"},"409":{"description":"Cannot delete brigade with active calls"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/brigades/{id}/members":{"get":{"tags":["Brigades"],"summary":"Get brigade members","description":"Retrieve all members of a specific brigade","security":[{"BearerAuth":[]}],"parameters":[{"name":"id","in":"path","required":true,"description":"Brigade ID","schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Brigade members retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"userId":{"type":"string","format":"uuid"},"role":{"type":"string","enum":["leader","member"]},"joinedAt":{"type":"string","format":"date-time"},"user":{"$ref":"#/components/schemas/User"}}}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"404":{"$ref":"#/components/responses/NotFoundError"},"500":{"$ref":"#/components/responses/InternalServerError"}}},"post":{"tags":["Brigades"],"summary":"Add member to brigade","description":"Add a user as a member to a brigade (Admin/Dispatcher only)","security":[{"BearerAuth":[]}],"parameters":[{"name":"id","in":"path","required":true,"description":"Brigade ID","schema":{"type":"string","format":"uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["userId"],"properties":{"userId":{"type":"string","format":"uuid"},"role":{"type":"string","enum":["leader","member"],"default":"member"}}},"example":{"userId":"123e4567-e89b-12d3-a456-426614174000","role":"member"}}}},"responses":{"201":{"description":"Member added to brigade successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"message":{"type":"string","example":"Member added to brigade successfully"}}}}}},"400":{"$ref":"#/components/responses/ValidationError"},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Insufficient permissions"},"404":{"$ref":"#/components/responses/NotFoundError"},"409":{"description":"User is already a member of this brigade"},"500":{"$ref":"#/components/responses/InternalServerError"}}},"put":{"tags":["Brigades"],"summary":"Update/Reassign brigade member","description":"Update a brigade member's role or reassign them to a different brigade (Admin/Dispatcher only)","security":[{"BearerAuth":[]}],"parameters":[{"name":"id","in":"path","required":true,"description":"Target Brigade ID (where the member will be assigned)","schema":{"type":"string","format":"uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["userId","role"],"properties":{"userId":{"type":"string","format":"uuid","description":"ID of the user to update/reassign"},"role":{"type":"string","enum":["leader","member"],"description":"New role for the member"}}},"example":{"userId":"123e4567-e89b-12d3-a456-426614174000","role":"leader"}}}},"responses":{"200":{"description":"Brigade member updated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"message":{"type":"string","example":"Brigade member updated successfully"}}}}}},"400":{"$ref":"#/components/responses/ValidationError"},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Insufficient permissions"},"404":{"description":"Brigade not found or member not found"},"409":{"description":"Brigade already has a leader (when trying to assign leader role)"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/brigades/{id}/members/{userId}":{"delete":{"tags":["Brigades"],"summary":"Remove member from brigade","description":"Remove a user from a brigade (Admin/Dispatcher only)","security":[{"BearerAuth":[]}],"parameters":[{"name":"id","in":"path","required":true,"description":"Brigade ID","schema":{"type":"string","format":"uuid"}},{"name":"userId","in":"path","required":true,"description":"User ID to remove","schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Member removed from brigade successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"message":{"type":"string","example":"Member removed from brigade successfully"}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Insufficient permissions"},"404":{"$ref":"#/components/responses/NotFoundError"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/brigades/{id}/location":{"get":{"tags":["Brigades"],"summary":"Get brigade location","description":"Get the current location of a brigade","security":[{"BearerAuth":[]}],"parameters":[{"name":"id","in":"path","required":true,"description":"Brigade ID","schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Brigade location retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"object","properties":{"brigadeId":{"type":"string","format":"uuid"},"currentLocation":{"type":"object","properties":{"lat":{"type":"number","format":"double"},"lng":{"type":"number","format":"double"}}}}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Access denied"},"404":{"$ref":"#/components/responses/NotFoundError"},"500":{"$ref":"#/components/responses/InternalServerError"}}},"put":{"tags":["Brigades"],"summary":"Update brigade location","description":"Update the current location of a brigade (Brigade members only)","security":[{"BearerAuth":[]}],"parameters":[{"name":"id","in":"path","required":true,"description":"Brigade ID","schema":{"type":"string","format":"uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["latitude","longitude"],"properties":{"latitude":{"type":"number","format":"double","minimum":-90,"maximum":90},"longitude":{"type":"number","format":"double","minimum":-180,"maximum":180},"address":{"type":"string","maxLength":255}}},"example":{"latitude":40.7128,"longitude":-74.006,"address":"New York, NY, USA"}}}},"responses":{"200":{"description":"Brigade location updated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"message":{"type":"string","example":"Brigade location updated successfully"}}}}}},"400":{"$ref":"#/components/responses/ValidationError"},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Only brigade members can update location"},"404":{"$ref":"#/components/responses/NotFoundError"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/brigades/calls/{callId}/accept":{"post":{"tags":["Brigades"],"summary":"Brigade accepts a pending call (taxi app style)","description":"Brigade leader accepts a pending call before dispatcher assignment.\nSimilar to taxi apps where drivers claim rides - brigades can claim pending calls.\nOnly brigade leaders can accept calls, and only pending calls can be accepted.\n","security":[{"BearerAuth":[]}],"parameters":[{"name":"callId","in":"path","required":true,"description":"Call ID to accept","schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Call accepted successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Call accepted successfully"},"data":{"type":"object","properties":{"brigadeId":{"type":"string","format":"uuid"},"callId":{"type":"string","format":"uuid"},"message":{"type":"string"}}}}}}}},"400":{"description":"Invalid request (call not pending, already accepted, etc.)","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string","example":"Call is not in pending status"}}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Only brigade leaders can accept calls"},"404":{"$ref":"#/components/responses/NotFoundError"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/brigades/calls/{callId}/reject":{"post":{"tags":["Brigades"],"summary":"Brigade rejects a pending call (auto-reassignment)","description":"Brigade member rejects a pending call notification.\nSystem automatically finds another available brigade and notifies them.\nSimilar to taxi apps - if one driver declines, the next one gets notified.\n","security":[{"BearerAuth":[]}],"parameters":[{"name":"callId","in":"path","required":true,"description":"Call ID to reject","schema":{"type":"string","format":"uuid"}}],"requestBody":{"required":false,"content":{"application/json":{"schema":{"type":"object","properties":{"reason":{"type":"string","maxLength":500,"description":"Optional reason for rejection"}}},"examples":{"with_reason":{"summary":"Reject with reason","value":{"reason":"Currently handling another emergency"}},"without_reason":{"summary":"Reject without reason","value":{}}}}}},"responses":{"200":{"description":"Call rejected and reassigned to another brigade","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Call rejected, finding another brigade"},"data":{"type":"object","properties":{"brigadeId":{"type":"string","format":"uuid","description":"ID of brigade that rejected"},"callId":{"type":"string","format":"uuid"},"message":{"type":"string"},"reassignedTo":{"type":"string","format":"uuid","description":"ID of brigade that was notified next (if available)"}}}}}}}},"400":{"description":"Invalid request (call not pending, etc.)"},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Only brigade members can reject calls"},"404":{"$ref":"#/components/responses/NotFoundError"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/brigades/calls/{callId}/respond":{"post":{"tags":["Brigades"],"summary":"Brigade responds to call assignment","description":"Brigade member accepts or rejects a call assignment (for already assigned calls)","security":[{"BearerAuth":[]}],"parameters":[{"name":"callId","in":"path","required":true,"description":"Call ID to respond to","schema":{"type":"string","format":"uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["response"],"properties":{"response":{"type":"string","enum":["accepted","rejected"],"description":"Brigade response to the call assignment"},"reason":{"type":"string","maxLength":500,"description":"Optional reason for rejection"}}},"examples":{"accept":{"summary":"Accept call","value":{"response":"accepted"}},"reject":{"summary":"Reject call with reason","value":{"response":"rejected","reason":"Currently handling another emergency"}}}}}},"responses":{"201":{"description":"Brigade response recorded successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"callId":{"type":"string","format":"uuid"},"brigadeId":{"type":"string","format":"uuid"},"userId":{"type":"string","format":"uuid"},"response":{"type":"string","enum":["accepted","rejected"]},"responseTime":{"type":"string","format":"date-time"},"reason":{"type":"string"}}},"message":{"type":"string","example":"Call accepted successfully"}}}}}},"400":{"$ref":"#/components/responses/ValidationError"},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Only brigade members can respond to calls"},"404":{"description":"Call not found or not assigned to your brigade"},"409":{"description":"Brigade has already responded to this call"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/brigades/calls/{callId}/responses":{"get":{"tags":["Brigades"],"summary":"Get brigade response history for a call","description":"Retrieve all brigade responses for a specific call (Admin/Dispatcher only)","security":[{"BearerAuth":[]}],"parameters":[{"name":"callId","in":"path","required":true,"description":"Call ID to get response history for","schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Brigade response history retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"callId":{"type":"string","format":"uuid"},"brigadeId":{"type":"string","format":"uuid"},"userId":{"type":"string","format":"uuid"},"response":{"type":"string","enum":["accepted","rejected","timeout"]},"responseTime":{"type":"string","format":"date-time"},"reason":{"type":"string"},"brigadeName":{"type":"string"},"respondedBy":{"type":"string"}}}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Insufficient permissions"},"404":{"$ref":"#/components/responses/NotFoundError"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/brigades/calls/{callId}/manual-assign":{"post":{"tags":["Brigades"],"summary":"Manually assign brigade to call","description":"Dispatcher manually assigns a brigade to a call after rejections/timeouts (Admin/Dispatcher only)","security":[{"BearerAuth":[]}],"parameters":[{"name":"callId","in":"path","required":true,"description":"Call ID to assign brigade to","schema":{"type":"string","format":"uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["brigadeId"],"properties":{"brigadeId":{"type":"string","format":"uuid","description":"Brigade ID to assign to the call"},"reason":{"type":"string","maxLength":500,"description":"Optional reason for manual assignment"},"override":{"type":"boolean","default":false,"description":"Override existing assignment"}}},"example":{"brigadeId":"123e4567-e89b-12d3-a456-426614174000","reason":"Manually assigned due to multiple rejections","override":false}}}},"responses":{"200":{"description":"Brigade manually assigned successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/Call"},"message":{"type":"string","example":"Brigade manually assigned successfully"}}}}}},"400":{"$ref":"#/components/responses/ValidationError"},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Insufficient permissions"},"404":{"description":"Call or brigade not found"},"409":{"description":"Call is not in assignable status"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/brigades/calls/pending":{"get":{"tags":["Brigades"],"summary":"Get calls requiring manual assignment","description":"Retrieve calls that need manual dispatcher assignment due to rejections or timeouts (Admin/Dispatcher only)","security":[{"BearerAuth":[]}],"responses":{"200":{"description":"Pending calls retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"title":{"type":"string"},"type":{"type":"string","enum":["emergency","scheduled","patrol","maintenance"]},"priority":{"type":"string","enum":["low","medium","high","critical"]},"status":{"type":"string","example":"pending"},"address":{"type":"string"},"coordinates":{"type":"object","properties":{"lat":{"type":"number"},"lng":{"type":"number"}}},"createdAt":{"type":"string","format":"date-time"},"updatedAt":{"type":"string","format":"date-time"},"clientName":{"type":"string"},"clientPhone":{"type":"string"},"rejectionCount":{"type":"integer","description":"Number of times brigades rejected this call"},"lastRejectionTime":{"type":"string","format":"date-time"},"assignmentAttempts":{"type":"integer","description":"Number of assignment attempts made"}}}},"count":{"type":"integer","description":"Total number of pending calls"}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Insufficient permissions"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/calls/active":{"get":{"tags":["Calls"],"summary":"Get active call for current user","description":"Retrieve the current user's active call (pending, assigned, en_route, in_progress, or arrived status)","security":[{"BearerAuth":[]}],"responses":{"200":{"description":"Active call retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/CallWithDetails"}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"404":{"description":"No active call found","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"No active call found"}}}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/calls":{"get":{"tags":["Calls"],"summary":"Get all calls","description":"Retrieve a paginated list of calls with optional filtering","security":[{"BearerAuth":[]}],"parameters":[{"$ref":"#/components/parameters/PageParam"},{"$ref":"#/components/parameters/LimitParam"},{"$ref":"#/components/parameters/SortParam"},{"name":"status","in":"query","description":"Filter by call status","schema":{"type":"string","enum":["pending","assigned","in_progress","completed","cancelled"]}},{"name":"priority","in":"query","description":"Filter by call priority","schema":{"type":"string","enum":["low","medium","high","critical"]}},{"name":"type","in":"query","description":"Filter by call type","schema":{"type":"string","enum":["emergency","security","maintenance","consultation"]}},{"name":"clientId","in":"query","description":"Filter by client ID","schema":{"type":"string","format":"uuid"}},{"name":"brigadeId","in":"query","description":"Filter by brigade ID","schema":{"type":"string","format":"uuid"}},{"name":"search","in":"query","description":"Search by call title or address","schema":{"type":"string"}}],"responses":{"200":{"description":"Calls retrieved successfully","content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/PaginatedResponse"},{"type":"object","properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/Call"}}}}]}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"500":{"$ref":"#/components/responses/InternalServerError"}}},"post":{"tags":["Calls"],"summary":"Create a new call","description":"Create a new emergency or service call","security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["type","priority","title","address"],"properties":{"type":{"type":"string","enum":["emergency","security","maintenance","consultation"]},"priority":{"type":"string","enum":["low","medium","high","critical"]},"title":{"type":"string","maxLength":255},"description":{"type":"string","maxLength":2000},"address":{"type":"string"},"coordinates":{"type":"object","properties":{"latitude":{"type":"number","format":"double","minimum":-90,"maximum":90},"longitude":{"type":"number","format":"double","minimum":-180,"maximum":180}}},"estimatedDuration":{"type":"integer","minimum":1}}},"example":{"type":"emergency","priority":"high","title":"Security breach at main entrance","description":"Unauthorized access detected at the main building entrance","address":"123 Main Street, City, State","coordinates":{"latitude":40.7128,"longitude":-74.006},"estimatedDuration":30}}}},"responses":{"201":{"description":"Call created successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/Call"}}}}}},"400":{"$ref":"#/components/responses/ValidationError"},"401":{"$ref":"#/components/responses/UnauthorizedError"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/calls/{id}":{"get":{"tags":["Calls"],"summary":"Get call by ID","description":"Retrieve a specific call by its ID","security":[{"BearerAuth":[]}],"parameters":[{"name":"id","in":"path","required":true,"description":"Call ID","schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Call retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/Call"}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"404":{"$ref":"#/components/responses/NotFoundError"},"500":{"$ref":"#/components/responses/InternalServerError"}}},"put":{"tags":["Calls"],"summary":"Update call","description":"Update an existing call (admin/dispatcher only)","security":[{"BearerAuth":[]}],"parameters":[{"name":"id","in":"path","required":true,"description":"Call ID","schema":{"type":"string","format":"uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"status":{"type":"string","enum":["pending","assigned","in_progress","completed","cancelled"]},"brigadeId":{"type":"string","format":"uuid","nullable":true},"priority":{"type":"string","enum":["low","medium","high","critical"]},"estimatedDuration":{"type":"integer","minimum":1},"actualDuration":{"type":"integer","minimum":1},"totalCost":{"type":"number","format":"decimal","minimum":0}}},"example":{"status":"assigned","brigadeId":"456e7890-e89b-12d3-a456-426614174000","priority":"high"}}}},"responses":{"200":{"description":"Call updated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/Call"}}}}}},"400":{"$ref":"#/components/responses/ValidationError"},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Insufficient permissions","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string","example":"Insufficient permissions to update call"}}}}}}}},"404":{"$ref":"#/components/responses/NotFoundError"},"500":{"$ref":"#/components/responses/InternalServerError"}}},"delete":{"tags":["Calls"],"summary":"Delete call","description":"Delete a call (admin only)","security":[{"BearerAuth":[]}],"parameters":[{"name":"id","in":"path","required":true,"description":"Call ID","schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Call deleted successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Call deleted successfully"}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Insufficient permissions"},"404":{"$ref":"#/components/responses/NotFoundError"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/calls/{id}/assign":{"post":{"tags":["Calls"],"summary":"Assign call to brigade","description":"Assign a call to a specific brigade (dispatcher/admin only)","security":[{"BearerAuth":[]}],"parameters":[{"name":"id","in":"path","required":true,"description":"Call ID","schema":{"type":"string","format":"uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["brigadeId"],"properties":{"brigadeId":{"type":"string","format":"uuid"}}},"example":{"brigadeId":"456e7890-e89b-12d3-a456-426614174000"}}}},"responses":{"200":{"description":"Call assigned successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/Call"},"message":{"type":"string","example":"Call assigned to brigade successfully"}}}}}},"400":{"$ref":"#/components/responses/ValidationError"},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Insufficient permissions"},"404":{"$ref":"#/components/responses/NotFoundError"},"409":{"description":"Brigade not available","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string","example":"Brigade is not available for assignment"}}}}}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/calls/{id}/status":{"patch":{"tags":["Calls"],"summary":"Update call status","description":"Update the status of a call (brigade members can update assigned calls)","security":[{"BearerAuth":[]}],"parameters":[{"name":"id","in":"path","required":true,"description":"Call ID","schema":{"type":"string","format":"uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["status"],"properties":{"status":{"type":"string","enum":["in_progress","completed","cancelled"]},"notes":{"type":"string","maxLength":1000}}},"example":{"status":"in_progress","notes":"Brigade arrived on scene, investigating the issue"}}}},"responses":{"200":{"description":"Call status updated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/Call"}}}}}},"400":{"$ref":"#/components/responses/ValidationError"},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Cannot update call status"},"404":{"$ref":"#/components/responses/NotFoundError"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/calls/brigades/available":{"get":{"tags":["Calls"],"summary":"Get available brigades","description":"Retrieve a list of brigades with active status that are available for call assignment (dispatcher/admin only)","security":[{"BearerAuth":[]}],"responses":{"200":{"description":"Available brigades retrieved successfully","content":{"application/json":{"schema":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"name":{"type":"string"},"status":{"type":"string","example":"active"},"currentLocation":{"type":"object","nullable":true,"properties":{"lat":{"type":"number","format":"double"},"lng":{"type":"number","format":"double"}}}}}},"example":[{"id":"456e7890-e89b-12d3-a456-426614174000","name":"Brigade Alpha","status":"active","currentLocation":{"lat":42.8746,"lng":74.5698}},{"id":"789e0123-e89b-12d3-a456-426614174000","name":"Brigade Beta","status":"active","currentLocation":null}]}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Access denied - only dispatchers and admins can view available brigades","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","example":"Access denied"}}}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/cars":{"get":{"tags":["Cars"],"summary":"Get all cars","description":"Retrieve a list of all cars. Requires authentication.","security":[{"BearerAuth":[]}],"responses":{"200":{"description":"List of all cars","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/Car"}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"500":{"$ref":"#/components/responses/InternalServerError"}}},"post":{"tags":["Cars"],"summary":"Create a new car","description":"Create a new car record. Only admins and dispatchers can create cars.","security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateCarRequest"},"example":{"licensePlate":"01KG123ABC","model":"Toyota Camry","year":2023,"color":"white","status":"active","gpsDeviceId":"GPS-001","brigadeId":"123e4567-e89b-12d3-a456-426614174000"}}}},"responses":{"201":{"description":"Car created successfully","content":{"application/json":{"schema":{"type":"object","properties":{"carId":{"type":"string","format":"uuid","description":"ID of the newly created car"}}}}}},"400":{"description":"Validation error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Invalid request data"},"errors":{"type":"array","items":{"type":"string"}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Access denied - only admins and dispatchers can create cars","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Access denied. Only admins and dispatchers can create cars."}}}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/cars/{carId}":{"get":{"tags":["Cars"],"summary":"Get car by ID","description":"Retrieve a specific car by its ID. Requires authentication.","security":[{"BearerAuth":[]}],"parameters":[{"name":"carId","in":"path","required":true,"description":"Car ID","schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Car details retrieved successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Car"}}}},"400":{"description":"Car ID is required","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Car ID is required"}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"404":{"description":"Car not found","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Car not found"}}}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}},"put":{"tags":["Cars"],"summary":"Update car","description":"Update an existing car. Only admins and dispatchers can update cars.","security":[{"BearerAuth":[]}],"parameters":[{"name":"carId","in":"path","required":true,"description":"Car ID","schema":{"type":"string","format":"uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateCarRequest"},"example":{"model":"Toyota Camry 2024","color":"black","status":"maintenance"}}}},"responses":{"200":{"description":"Car updated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Car updated successfully"}}}}}},"400":{"description":"Validation error or missing Car ID","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Invalid request data"},"errors":{"type":"array","items":{"type":"string"}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Access denied - only admins and dispatchers can update cars","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Access denied. Only admins and dispatchers can update cars."}}}}}},"404":{"description":"Car not found","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Car not found"}}}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}},"delete":{"tags":["Cars"],"summary":"Delete car","description":"Delete a car. Only admins can delete cars.","security":[{"BearerAuth":[]}],"parameters":[{"name":"carId","in":"path","required":true,"description":"Car ID","schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Car deleted successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Car deleted successfully"}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Access denied - only admins can delete cars","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Access denied. Only admins can delete cars."}}}}}},"404":{"description":"Car not found","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Car not found"}}}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/chat/{callId}/messages":{"get":{"tags":["Chat"],"summary":"Get chat messages for a call","description":"Retrieve paginated chat messages for a specific call","security":[{"BearerAuth":[]}],"parameters":[{"name":"callId","in":"path","required":true,"description":"Call ID","schema":{"type":"string","format":"uuid"}},{"$ref":"#/components/parameters/PageParam"},{"$ref":"#/components/parameters/LimitParam"},{"name":"before","in":"query","description":"Get messages before this timestamp (for pagination)","schema":{"type":"string","format":"date-time"}}],"responses":{"200":{"description":"Messages retrieved successfully","content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/PaginatedResponse"},{"type":"object","properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/ChatMessage"}}}}]}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Access denied to this call","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string","example":"Call not found or access denied"}}}}}}}},"404":{"$ref":"#/components/responses/NotFoundError"},"500":{"$ref":"#/components/responses/InternalServerError"}}},"post":{"tags":["Chat"],"summary":"Send a chat message","description":"Send a new message in a call chat","security":[{"BearerAuth":[]}],"parameters":[{"name":"callId","in":"path","required":true,"description":"Call ID","schema":{"type":"string","format":"uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["message"],"properties":{"message":{"type":"string","maxLength":1000,"minLength":1},"messageType":{"type":"string","enum":["text","image","location","file"],"default":"text"},"fileUrl":{"type":"string","format":"uri","description":"URL of attached file (for image/file messages)"}}},"example":{"message":"We are en route to your location","messageType":"text"}}}},"responses":{"201":{"description":"Message sent successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/ChatMessage"}}}}}},"400":{"$ref":"#/components/responses/ValidationError"},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Access denied to this call"},"404":{"$ref":"#/components/responses/NotFoundError"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/chat/{callId}/messages/read":{"put":{"tags":["Chat"],"summary":"Mark messages as read","description":"Mark specific messages as read by the current user","security":[{"BearerAuth":[]}],"parameters":[{"name":"callId","in":"path","required":true,"description":"Call ID","schema":{"type":"string","format":"uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["messageIds"],"properties":{"messageIds":{"type":"array","items":{"type":"string","format":"uuid"},"minItems":1,"maxItems":100}}},"example":{"messageIds":["123e4567-e89b-12d3-a456-426614174000","456e7890-e89b-12d3-a456-426614174001"]}}}},"responses":{"200":{"description":"Messages marked as read successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"object","properties":{"markedAsRead":{"type":"integer","example":2}}}}}}}},"400":{"$ref":"#/components/responses/ValidationError"},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Access denied to this call"},"404":{"$ref":"#/components/responses/NotFoundError"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/chat/{callId}/unread-count":{"get":{"tags":["Chat"],"summary":"Get unread message count","description":"Get the count of unread messages for a specific call","security":[{"BearerAuth":[]}],"parameters":[{"name":"callId","in":"path","required":true,"description":"Call ID","schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Unread count retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"object","properties":{"unreadCount":{"type":"integer","example":5}}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Access denied to this call"},"404":{"$ref":"#/components/responses/NotFoundError"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/chat/unread-messages":{"get":{"tags":["Chat"],"summary":"Get all unread messages","description":"Get all unread messages across all calls for the current user","security":[{"BearerAuth":[]}],"responses":{"200":{"description":"Unread messages retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"array","items":{"allOf":[{"$ref":"#/components/schemas/ChatMessage"},{"type":"object","properties":{"call":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"title":{"type":"string"},"status":{"type":"string","enum":["pending","assigned","en_route","arrived","in_progress","completed","cancelled"]}}}}}]}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/chat/upload":{"post":{"tags":["Chat"],"summary":"Upload file for chat","description":"Upload a file (image, document) to be used in chat messages","security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"multipart/form-data":{"schema":{"type":"object","required":["file"],"properties":{"file":{"type":"string","format":"binary","description":"File to upload (max 10MB)"},"callId":{"type":"string","format":"uuid","description":"Associated call ID"}}}}}},"responses":{"200":{"description":"File uploaded successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"object","properties":{"fileUrl":{"type":"string","format":"uri","example":"https://s3.amazonaws.com/bucket/chat/file123.jpg"},"fileName":{"type":"string","example":"image.jpg"},"fileSize":{"type":"integer","example":1024000},"mimeType":{"type":"string","example":"image/jpeg"}}}}}}}},"400":{"description":"Invalid file or validation error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string","example":"File size exceeds 10MB limit"}}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"413":{"description":"File too large"},"415":{"description":"Unsupported file type"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/client-addresses/all":{"get":{"summary":"Get all client addresses (admin/dispatcher)","description":"Get paginated list of all client addresses across all users.\nOnly accessible by admin and dispatcher roles.\nIncludes user info (name, email, phone) for each address.\n","tags":["Client Addresses"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"query","name":"page","schema":{"type":"integer","minimum":1,"default":1},"description":"Page number for pagination"},{"in":"query","name":"limit","schema":{"type":"integer","minimum":1,"maximum":100,"default":20},"description":"Number of items per page"},{"in":"query","name":"search","schema":{"type":"string"},"description":"Search in address name, address text, or client name"},{"in":"query","name":"userId","schema":{"type":"string","format":"uuid"},"description":"Filter addresses by specific user ID"},{"in":"query","name":"isDefault","schema":{"type":"boolean"},"description":"Filter by default address status"}],"responses":{"200":{"description":"All client addresses retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"array","items":{"allOf":[{"$ref":"#/components/schemas/ClientAddress"},{"type":"object","properties":{"user":{"type":"object","description":"Owner user info","properties":{"firstName":{"type":"string","example":"Иван"},"lastName":{"type":"string","example":"Иванов"},"email":{"type":"string","format":"email","example":"ivan@example.com"},"phone":{"type":"string","example":"+996555123456"}}}}}]}},"pagination":{"type":"object","properties":{"page":{"type":"integer","example":1},"limit":{"type":"integer","example":20},"total":{"type":"integer","example":45},"pages":{"type":"integer","example":3}}}}}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"Forbidden - requires admin or dispatcher role","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForbiddenError"}}}}}}},"/api/client-addresses":{"post":{"summary":"Create a new client address","description":"Create a new address for the authenticated user","tags":["Client Addresses"],"security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateClientAddressRequest"}}}},"responses":{"201":{"description":"Address created successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/ClientAddress"}}}}}},"400":{"description":"Validation failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidationError"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}}}},"get":{"summary":"Get user's addresses","description":"Get paginated list of addresses for the authenticated user","tags":["Client Addresses"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"query","name":"page","schema":{"type":"integer","minimum":1,"default":1},"description":"Page number for pagination"},{"in":"query","name":"limit","schema":{"type":"integer","minimum":1,"maximum":100,"default":20},"description":"Number of items per page"},{"in":"query","name":"search","schema":{"type":"string"},"description":"Search in address name or address text"},{"in":"query","name":"isDefault","schema":{"type":"boolean"},"description":"Filter by default address status"}],"responses":{"200":{"description":"Addresses retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/PaginatedClientAddresses"}}}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}}}}},"/api/client-addresses/default":{"get":{"summary":"Get user's default address","description":"Get the default address for the authenticated user","tags":["Client Addresses"],"security":[{"BearerAuth":[]}],"responses":{"200":{"description":"Default address retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/ClientAddress"}}}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"404":{"description":"No default address found","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string","example":"No default address found"}}}}}}}}}}},"/api/client-addresses/nearby":{"post":{"summary":"Find addresses near coordinates","description":"Find user's addresses within a specified radius of given coordinates","tags":["Client Addresses"],"security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/NearbySearchRequest"}}}},"responses":{"200":{"description":"Nearby addresses found","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"array","items":{"$ref":"#/components/schemas/ClientAddress"}}}}}}},"400":{"description":"Validation failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidationError"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}}}}},"/api/client-addresses/{id}":{"get":{"summary":"Get address by ID","description":"Get a specific address by its ID","tags":["Client Addresses"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"},"description":"Address ID"}],"responses":{"200":{"description":"Address retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/ClientAddress"}}}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"404":{"description":"Address not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/NotFoundError"}}}}}},"put":{"summary":"Update address","description":"Update an existing address","tags":["Client Addresses"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"},"description":"Address ID"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateClientAddressRequest"}}}},"responses":{"200":{"description":"Address updated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/ClientAddress"}}}}}},"400":{"description":"Validation failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidationError"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"404":{"description":"Address not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/NotFoundError"}}}}}},"delete":{"summary":"Delete address","description":"Delete an address (soft delete)","tags":["Client Addresses"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"},"description":"Address ID"}],"responses":{"200":{"description":"Address deleted successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Address deleted successfully"}}}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"404":{"description":"Address not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/NotFoundError"}}}}}}},"/api/client-addresses/{id}/default":{"put":{"summary":"Set address as default","description":"Set the specified address as the user's default address","tags":["Client Addresses"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"},"description":"Address ID"}],"responses":{"200":{"description":"Default address updated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Default address updated successfully"}}}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"404":{"description":"Address not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/NotFoundError"}}}}}}},"/api/connected-objects":{"post":{"summary":"Create a new connected object","description":"Create a new IoT device or connected object","tags":["Connected Objects"],"security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateConnectedObjectRequest"}}}},"responses":{"201":{"description":"Connected object created successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/ConnectedObject"}}}}}},"400":{"description":"Validation failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidationError"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"Access denied (clients can only create objects for themselves)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForbiddenError"}}}},"409":{"description":"Device ID already registered","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ConflictError"}}}}}},"get":{"summary":"Get connected objects","description":"Get paginated list of connected objects with filtering","tags":["Connected Objects"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"query","name":"page","schema":{"type":"integer","minimum":1,"default":1},"description":"Page number for pagination"},{"in":"query","name":"limit","schema":{"type":"integer","minimum":1,"maximum":100,"default":20},"description":"Number of items per page"},{"in":"query","name":"clientId","schema":{"type":"string","format":"uuid"},"description":"Filter by client ID (admins/dispatchers only)"},{"in":"query","name":"type","schema":{"type":"string","enum":["camera","sensor","alarm","lock","other"]},"description":"Filter by object type"},{"in":"query","name":"status","schema":{"type":"string","enum":["active","inactive","alarm","maintenance"]},"description":"Filter by object status (can be array)"},{"in":"query","name":"search","schema":{"type":"string"},"description":"Search in object name, device ID, or location"},{"in":"query","name":"hasAlarm","schema":{"type":"boolean"},"description":"Filter only objects in alarm state"}],"responses":{"200":{"description":"Connected objects retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/PaginatedConnectedObjects"}}}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}}}}},"/api/connected-objects/alarms":{"get":{"summary":"Get objects in alarm state","description":"Get paginated list of objects currently in alarm state (dispatchers/admins only)","tags":["Connected Objects"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"query","name":"page","schema":{"type":"integer","minimum":1,"default":1},"description":"Page number for pagination"},{"in":"query","name":"limit","schema":{"type":"integer","minimum":1,"maximum":100,"default":20},"description":"Number of items per page"}],"responses":{"200":{"description":"Alarm objects retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/PaginatedConnectedObjects"}}}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"Insufficient permissions","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForbiddenError"}}}}}}},"/api/connected-objects/client/{clientId}":{"get":{"summary":"Get objects by client ID","description":"Get paginated list of objects for a specific client","tags":["Connected Objects"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"clientId","required":true,"schema":{"type":"string","format":"uuid"},"description":"Client ID"},{"in":"query","name":"page","schema":{"type":"integer","minimum":1,"default":1},"description":"Page number for pagination"},{"in":"query","name":"limit","schema":{"type":"integer","minimum":1,"maximum":100,"default":20},"description":"Number of items per page"}],"responses":{"200":{"description":"Client objects retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/PaginatedConnectedObjects"}}}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"Access denied (clients can only see their own objects)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForbiddenError"}}}}}}},"/api/connected-objects/{id}":{"get":{"summary":"Get connected object by ID","description":"Get a specific connected object by its ID","tags":["Connected Objects"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"},"description":"Connected object ID"}],"responses":{"200":{"description":"Connected object retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/ConnectedObjectWithClient"}}}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"Access denied (clients can only see their own objects)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForbiddenError"}}}},"404":{"description":"Connected object not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/NotFoundError"}}}}}},"put":{"summary":"Update connected object","description":"Update an existing connected object","tags":["Connected Objects"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"},"description":"Connected object ID"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateConnectedObjectRequest"}}}},"responses":{"200":{"description":"Connected object updated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/ConnectedObjectWithClient"}}}}}},"400":{"description":"Validation failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidationError"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"Access denied (clients can only update their own objects)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForbiddenError"}}}},"404":{"description":"Connected object not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/NotFoundError"}}}}}},"delete":{"summary":"Delete connected object","description":"Delete a connected object (soft delete)","tags":["Connected Objects"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"},"description":"Connected object ID"}],"responses":{"200":{"description":"Connected object deleted successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Connected object deleted successfully"}}}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"Access denied (clients can only delete their own objects)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForbiddenError"}}}},"404":{"description":"Connected object not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/NotFoundError"}}}}}}},"/api/connected-objects/device/{deviceId}/status":{"post":{"summary":"Update device status","description":"Update device status for IoT device heartbeats (no authentication required for devices)","tags":["Connected Objects"],"parameters":[{"in":"path","name":"deviceId","required":true,"schema":{"type":"string"},"description":"Device ID"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/DeviceStatusUpdateRequest"}}}},"responses":{"200":{"description":"Device status updated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Device status updated successfully"}}}}}},"400":{"description":"Validation failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidationError"}}}},"404":{"description":"Device not found","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string","example":"Device not found"}}}}}}}}}}},"/api/corporate/entity":{"get":{"tags":["Corporate Management"],"summary":"Get list of legal entities","description":"Get paginated list of legal entities with optional filtering by status, search query, industry, and verification status. Admin only.","security":[{"BearerAuth":[]}],"parameters":[{"name":"page","in":"query","description":"Page number","schema":{"type":"integer","minimum":1,"default":1}},{"name":"limit","in":"query","description":"Number of items per page","schema":{"type":"integer","minimum":1,"maximum":100,"default":20}},{"name":"status","in":"query","description":"Filter by entity status","schema":{"type":"string","enum":["active","suspended","inactive"]}},{"name":"search","in":"query","description":"Search by company name, legal name, or tax ID","schema":{"type":"string"}},{"name":"industry","in":"query","description":"Filter by industry","schema":{"type":"string"}},{"name":"verified","in":"query","description":"Filter by verification status","schema":{"type":"boolean"}}],"responses":{"200":{"description":"Legal entities retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"array","items":{"$ref":"#/components/schemas/LegalEntity"}},"pagination":{"type":"object","properties":{"page":{"type":"integer"},"limit":{"type":"integer"},"total":{"type":"integer"},"totalPages":{"type":"integer"}}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Access denied - only admins can view all legal entities","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Access denied. Only admins can view all legal entities."}}}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}},"post":{"tags":["Corporate Management"],"summary":"Create legal entity","description":"Create a new legal entity. Admin only. Subject to legal_entities quota check.","security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateLegalEntityRequest"},"example":{"companyName":"SecuriTech KG","legalName":"OOO SecuriTech","taxId":"123456789","registrationNumber":"REG-001","email":"info@securitech.kg","phone":"+996555123456","website":"https://securitech.kg","legalAddress":"Bishkek, Chuy Ave 123","billingAddress":"Bishkek, Chuy Ave 123","industry":"Security","employeeCount":50,"description":"Corporate security services"}}}},"responses":{"201":{"description":"Legal entity created successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Legal entity created successfully"},"data":{"type":"object","properties":{"entityId":{"type":"string","format":"uuid"}}}}}}}},"400":{"description":"Validation error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Invalid request data"},"errors":{"type":"array","items":{"type":"string"}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Access denied - only admins can create legal entities, or quota exceeded","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Access denied. Only admins can create legal entities."}}}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/corporate/entity/{entityId}":{"get":{"tags":["Corporate Management"],"summary":"Get legal entity by ID with all related data","description":"Get complete information about a legal entity including employees, locations, recent calls, and statistics. Admin only.","security":[{"BearerAuth":[]}],"parameters":[{"name":"entityId","in":"path","required":true,"description":"Legal entity ID","schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Legal entity retrieved successfully with all related data","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"object","properties":{"entity":{"$ref":"#/components/schemas/LegalEntity"},"employees":{"type":"array","items":{"$ref":"#/components/schemas/CorporateEmployee"}},"locations":{"type":"array","items":{"$ref":"#/components/schemas/CorporateLocation"}},"calls":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"title":{"type":"string"},"status":{"type":"string"},"priority":{"type":"string"},"createdAt":{"type":"string","format":"date-time"}}}},"statistics":{"type":"object","properties":{"totalEmployees":{"type":"integer"},"activeEmployees":{"type":"integer"},"totalLocations":{"type":"integer"},"activeLocations":{"type":"integer"},"totalCalls":{"type":"integer"},"activeCalls":{"type":"integer"}}}}}}}}}},"400":{"description":"Entity ID is required","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Entity ID is required"}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Access denied - only admins can view legal entity details","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Access denied. Only admins can view legal entity details."}}}}}},"404":{"description":"Legal entity not found","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Legal entity not found"}}}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/corporate/locations":{"post":{"tags":["Corporate Management"],"summary":"Add corporate location","description":"Add a new location to a legal entity. Subject to corporate_locations\nquota check.\n\n`contactPerson` and `contactPhone` are optional and accept an empty\nstring, which is stored as no value — a client may post its blank form\nfields as `\"\"`.\n","security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AddCorporateLocationRequest"},"example":{"legalEntityId":"123e4567-e89b-12d3-a456-426614174000","name":"Main Office","address":"Bishkek, Chuy Ave 123","coordinates":{"lat":42.8746,"lng":74.5698},"locationType":"office","servicesEnabled":["alarm","patrol"],"contactPerson":"John Doe","contactPhone":"+996555123456"}}}},"responses":{"201":{"description":"Corporate location added successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Corporate location added successfully"},"data":{"type":"object","properties":{"locationId":{"type":"string","format":"uuid"}}}}}}}},"400":{"description":"Validation error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Invalid request data"},"errors":{"type":"array","items":{"type":"string"}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Quota exceeded"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/corporate/locations/{legalEntityId}":{"get":{"tags":["Corporate Management"],"summary":"Get corporate locations","description":"Retrieve all locations for a specific legal entity.","security":[{"BearerAuth":[]}],"parameters":[{"name":"legalEntityId","in":"path","required":true,"description":"Legal entity ID","schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Corporate locations retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"array","items":{"$ref":"#/components/schemas/CorporateLocation"}}}}}}},"400":{"description":"Legal entity ID is required","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Legal entity ID is required"}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/corporate/locations/{locationId}":{"put":{"tags":["Corporate Management"],"summary":"Update corporate location","description":"Update an existing corporate location. Requires legalEntityId in the request body.","security":[{"BearerAuth":[]}],"parameters":[{"name":"locationId","in":"path","required":true,"description":"Corporate location ID","schema":{"type":"string","format":"uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateCorporateLocationRequest"},"example":{"legalEntityId":"123e4567-e89b-12d3-a456-426614174000","name":"Updated Office Name","address":"Bishkek, Manas Ave 456","locationType":"office","contactPerson":"Jane Doe"}}}},"responses":{"200":{"description":"Corporate location updated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Corporate location updated successfully"}}}}}},"400":{"description":"Validation error or missing required IDs","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Invalid request data"},"errors":{"type":"array","items":{"type":"string"}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"404":{"description":"Corporate location not found","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Corporate location not found"}}}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/corporate/employees/lookup-or-invite":{"post":{"tags":["Corporate Management"],"summary":"Look up or invite an employee by email or phone","description":"Finds an existing user by email or phone and returns their details.\nIf no user is found, creates a new account with a temporary password,\nsends an invitation email (when email is provided), and returns the new user's ID.\nUse the returned `userId` to then call `POST /api/corporate/employees`.\n\nA phone resolves however it is written — the full digit string first,\nthen the trailing nine subscriber digits — so `+996555123456` and\n`0555123456` find the same colleague instead of creating a second\naccount for them. When the number matches several accounts and was not\ngiven in full, the request is refused with `PHONE_IDENTIFIER_AMBIGUOUS`;\nwhen an invite would attach a number another account already holds, with\n`PHONE_ALREADY_EXISTS`.\n","security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"email":{"type":"string","format":"email","description":"User's email address"},"phone":{"type":"string","maxLength":20,"description":"User's phone number"}}},"example":{"email":"ivan@example.com"}}}},"responses":{"200":{"description":"Lookup result — user found or new user created","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"object","properties":{"found":{"type":"boolean","description":"true if user already existed, false if a new account was created"},"userId":{"type":"string","format":"uuid"},"firstName":{"type":"string"},"lastName":{"type":"string"},"email":{"type":"string","nullable":true},"phone":{"type":"string","nullable":true}}}}}}}},"400":{"description":"Validation error — neither email nor phone was provided","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Укажите email или телефон"}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/corporate/employees":{"post":{"tags":["Corporate Management"],"summary":"Add corporate employee","description":"Add a user as an employee to a legal entity. Subject to employees quota\ncheck. `legalEntityId` is required and must be a UUID; `department` and\n`position` accept an empty string and treat it as omitted.\n","security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AddCorporateEmployeeRequest"},"example":{"legalEntityId":"123e4567-e89b-12d3-a456-426614174000","userId":"987e6543-e21b-12d3-a456-426614174000","department":"Security","position":"Guard","canMakeCalls":true,"accessLevel":"employee","employmentStartDate":"2024-01-15"}}}},"responses":{"201":{"description":"Corporate employee added successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Corporate employee added successfully"},"data":{"type":"object","properties":{"employeeId":{"type":"string","format":"uuid"}}}}}}}},"400":{"description":"Validation error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Invalid request data"},"errors":{"type":"array","items":{"type":"string"}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Quota exceeded"},"409":{"description":"The user is already an active employee of this legal entity\n(`USER_ALREADY_CORPORATE_EMPLOYEE`).\n","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Пользователь уже является сотрудником компании"},"code":{"type":"string","example":"USER_ALREADY_CORPORATE_EMPLOYEE"}}}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/corporate/employees/{legalEntityId}":{"get":{"tags":["Corporate Management"],"summary":"Get corporate employees","description":"Retrieve all employees for a specific legal entity.","security":[{"BearerAuth":[]}],"parameters":[{"name":"legalEntityId","in":"path","required":true,"description":"Legal entity ID","schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Corporate employees retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"array","items":{"$ref":"#/components/schemas/CorporateEmployee"}}}}}}},"400":{"description":"Legal entity ID is required","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Legal entity ID is required"}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/corporate/employees/{employeeId}":{"put":{"tags":["Corporate Management"],"summary":"Update corporate employee","description":"Update an existing corporate employee's department, position, call permissions, location access, or access level.","security":[{"BearerAuth":[]}],"parameters":[{"name":"employeeId","in":"path","required":true,"description":"Corporate employee ID","schema":{"type":"string","format":"uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateCorporateEmployeeRequest"},"example":{"department":"Operations","position":"Senior Guard","canMakeCalls":true,"accessLevel":"manager"}}}},"responses":{"200":{"description":"Corporate employee updated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Corporate employee updated successfully"}}}}}},"400":{"description":"Validation error or missing employee ID","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Invalid request data"},"errors":{"type":"array","items":{"type":"string"}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"404":{"description":"Corporate employee not found","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Корпоративный сотрудник не найден"}}}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}},"delete":{"tags":["Corporate Management"],"summary":"Remove corporate employee","description":"Remove (soft delete) a corporate employee. Requires legalEntityId as a query parameter. Decrements employees quota after successful removal.","security":[{"BearerAuth":[]}],"parameters":[{"name":"employeeId","in":"path","required":true,"description":"Corporate employee ID","schema":{"type":"string","format":"uuid"}},{"name":"legalEntityId","in":"query","required":true,"description":"Legal entity ID","schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Corporate employee removed successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Corporate employee removed successfully"}}}}}},"400":{"description":"Employee ID and legal entity ID are required","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Employee ID and legal entity ID are required"}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"404":{"description":"Corporate employee not found","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Corporate employee not found"}}}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/corporate/emergency-call":{"post":{"tags":["Corporate Management"],"summary":"Create corporate emergency call","description":"Create an emergency call for a corporate location. The user must have corporate access\n(be a corporate employee). Subject to emergency_calls quota check (default 50 calls/month).\nNotifies all corporate managers and admins via database notifications and Socket.IO.\n","security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateCorporateEmergencyCallRequest"},"example":{"locationId":"987e6543-e21b-12d3-a456-426614174000","description":"Unauthorized access detected at main entrance","eventType":"intrusion","severity":"critical"}}}},"responses":{"201":{"description":"Corporate emergency call created successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Corporate emergency call created successfully"},"data":{"type":"object","properties":{"callId":{"type":"string","format":"uuid"}}}}}}}},"400":{"description":"Validation error or user does not have corporate access","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"User does not have corporate access"}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Quota exceeded","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Emergency call quota exceeded"},"quotaInfo":{"type":"object","properties":{"quotaLimit":{"type":"integer","example":50},"quotaUsed":{"type":"integer","example":50},"quotaRemaining":{"type":"integer","example":0}}}}}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/corporate/my-access":{"get":{"tags":["Corporate Management"],"summary":"Get current user's corporate access","description":"Retrieve the corporate employee record for the authenticated user, if one exists. Returns null data if the user has no corporate access.","security":[{"BearerAuth":[]}],"responses":{"200":{"description":"Corporate access retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"oneOf":[{"$ref":"#/components/schemas/CorporateEmployee"},{"type":"null"}],"description":"Corporate employee record or null if no access"}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/device-tokens":{"post":{"summary":"Register or update a device token","description":"Register a new device token for push notifications or update an existing\none. Associates the token with the authenticated user and their device\nplatform.\n\nSide effect: when the caller is a `client` with `appType: \"client\"` who\nregistered within the last 7 days and has no active tariff — no own\nsubscription, not covered by a relative's family plan, not an active\ncorporate employee — a one-time welcome notification is sent explaining\nthat the panic button stays inactive until a tariff is chosen. The\nsign-up window keeps the message off long-standing accounts, for which\n\"you have successfully registered\" would be wrong. It is sent here because sign-up happens before\nany push token exists. At most one per user ever, enforced by\n`idx_notifications_subscription_welcome_once`; it is delivered as\n`system_alert` with `data.kind = \"subscription_welcome\"` and\n`data.screen = \"tariffs\"`. Failure to send never affects this response.\n","tags":["Device Tokens"],"security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RegisterDeviceTokenRequest"}}}},"responses":{"201":{"description":"Device token registered successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Device token registered successfully"},"data":{"type":"object","properties":{"tokenId":{"type":"string","format":"uuid","description":"Created or updated token ID"}}}}}}}},"400":{"description":"Validation error - invalid request data","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Invalid request data"},"errors":{"type":"array","items":{"type":"string"},"example":["\"token\" length must be at least 10 characters long","\"platform\" must be one of [ios, android, web]"]}}}}}},"401":{"description":"Unauthorized - invalid or missing JWT token","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Unauthorized"}}}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Internal server error"}}}}}}}},"get":{"summary":"Get user's device tokens","description":"Retrieve all active device tokens registered for the authenticated user","tags":["Device Tokens"],"security":[{"BearerAuth":[]}],"responses":{"200":{"description":"List of user's device tokens","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"object","properties":{"tokens":{"type":"array","items":{"$ref":"#/components/schemas/DeviceToken"}},"count":{"type":"integer","description":"Number of active tokens","example":2}}}}}}}},"401":{"description":"Unauthorized - invalid or missing JWT token","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Unauthorized"}}}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Internal server error"}}}}}}}}},"/api/device-tokens/deactivate-all":{"post":{"summary":"Deactivate all device tokens for current user (logout)","description":"Deactivates all active device tokens for the authenticated user. Call this before logout to stop receiving push notifications on all devices.","tags":["Device Tokens"],"security":[{"BearerAuth":[]}],"responses":{"200":{"description":"All device tokens deactivated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"All device tokens deactivated successfully"},"data":{"type":"object","properties":{"deactivatedCount":{"type":"integer","description":"Number of tokens deactivated","example":3}}}}}}}},"401":{"description":"Unauthorized - invalid or missing JWT token"},"500":{"description":"Internal server error"}}}},"/api/device-tokens/{tokenId}/deactivate":{"patch":{"summary":"Deactivate a device token","description":"Deactivate a specific device token. The token remains in the system but will no longer receive push notifications. Only the token owner can deactivate it.","tags":["Device Tokens"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"tokenId","required":true,"schema":{"type":"string","format":"uuid"},"description":"Device token ID to deactivate"}],"responses":{"200":{"description":"Device token deactivated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Device token deactivated successfully"}}}}}},"400":{"description":"Bad request - token ID is required","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Token ID is required"}}}}}},"401":{"description":"Unauthorized - invalid or missing JWT token","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Unauthorized"}}}}}},"404":{"description":"Device token not found","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Device token not found"}}}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Internal server error"}}}}}}}}},"/api/device-tokens/{tokenId}":{"delete":{"summary":"Remove a device token","description":"Permanently remove a specific device token from the system. Only the token owner can remove it.","tags":["Device Tokens"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"tokenId","required":true,"schema":{"type":"string","format":"uuid"},"description":"Device token ID to remove"}],"responses":{"200":{"description":"Device token removed successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Device token removed successfully"}}}}}},"400":{"description":"Bad request - token ID is required","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Token ID is required"}}}}}},"401":{"description":"Unauthorized - invalid or missing JWT token","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Unauthorized"}}}}}},"404":{"description":"Device token not found","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Device token not found"}}}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Internal server error"}}}}}}}}},"/api/device-tokens/cleanup":{"delete":{"summary":"Clean up inactive device tokens (Admin only)","description":"Remove device tokens that have been inactive for a specified number of days. Only accessible by admin users.","tags":["Device Tokens"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"query","name":"daysOld","schema":{"type":"integer","minimum":1,"maximum":365,"default":30},"description":"Remove tokens inactive for this many days (1-365)"}],"responses":{"200":{"description":"Inactive tokens cleaned up successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Inactive device tokens cleaned up successfully"},"data":{"type":"object","properties":{"deletedCount":{"type":"integer","description":"Number of tokens cleaned up","example":15}}}}}}}},"400":{"description":"Bad request - daysOld out of range","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"daysOld must be between 1 and 365"}}}}}},"401":{"description":"Unauthorized - invalid or missing JWT token","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Unauthorized"}}}}}},"403":{"description":"Forbidden - only admins can cleanup device tokens","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Access denied. Only admins can cleanup device tokens."}}}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Internal server error"}}}}}}}}},"/api/enhanced-profile/enhanced":{"get":{"tags":["Enhanced Profile"],"summary":"Get enhanced user profile","description":"Get comprehensive user profile with family, corporate, subscription, emergency contacts, medical info, and preferences context","security":[{"BearerAuth":[]}],"responses":{"200":{"description":"Enhanced profile retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/EnhancedUserProfile"}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Internal server error"}}}}}}}},"put":{"tags":["Enhanced Profile"],"summary":"Update user profile","description":"Update user profile fields including basic info, preferences, and medical information. All fields are optional.","security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateProfileRequest"}}}},"responses":{"200":{"description":"Profile updated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Profile updated successfully"}}}}}},"400":{"description":"Validation error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Invalid request data"},"errors":{"type":"array","items":{"type":"string"},"example":["\"first_name\" length must be less than or equal to 100 characters long"]}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Internal server error"}}}}}}}}},"/api/enhanced-profile/emergency-contacts":{"post":{"tags":["Enhanced Profile"],"summary":"Add emergency contact","description":"Add a new emergency contact to the authenticated user's profile","security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AddEmergencyContactRequest"}}}},"responses":{"201":{"description":"Emergency contact added successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Emergency contact added successfully"},"data":{"type":"object","properties":{"contactId":{"type":"string","format":"uuid","description":"ID of the newly created emergency contact","example":"880e8400-e29b-41d4-a716-446655440003"}}}}}}}},"400":{"description":"Validation error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Invalid request data"},"errors":{"type":"array","items":{"type":"string"},"example":["\"name\" is required"]}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Internal server error"}}}}}}}}},"/api/enhanced-profile/dashboard":{"get":{"tags":["Enhanced Profile"],"summary":"Get user dashboard data","description":"Get comprehensive dashboard with enhanced profile, recent calls, family activity, corporate activity, notifications, and context-aware quick actions","security":[{"BearerAuth":[]}],"responses":{"200":{"description":"Dashboard data retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/UserDashboard"}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Internal server error"}}}}}}}}},"/api/enhanced-profile/context":{"get":{"tags":["Enhanced Profile"],"summary":"Get user context summary","description":"Get a quick summary of the user's type, permissions, available services, and family/corporate context. Useful for determining UI state without loading the full enhanced profile.","security":[{"BearerAuth":[]}],"responses":{"200":{"description":"User context retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/UserContextSummary"}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Internal server error"}}}}}}}}},"/api/family/locations":{"get":{"tags":["Family Management"],"summary":"Get family member locations","description":"Get the last known locations of all family members for the authenticated user's\nfamily subscription. Locations are persisted from client mobile app socket events\n(`update_location`). Returns latitude, longitude, and timestamp of last update.\nAdmin/dispatcher can pass `?userId=` to query another user's family.\n","security":[{"BearerAuth":[]}],"parameters":[{"name":"userId","in":"query","required":false,"description":"(Admin/Dispatcher only) Target user whose family member locations to retrieve","schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Family member locations retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid","description":"Family member record ID"},"userId":{"type":"string","format":"uuid","description":"User ID of the family member"},"firstName":{"type":"string"},"lastName":{"type":"string"},"relationship":{"type":"string","enum":["child","spouse","parent","sibling","guardian","other"]},"latitude":{"type":"number","nullable":true,"description":"Last known latitude (null if no location data)"},"longitude":{"type":"number","nullable":true,"description":"Last known longitude (null if no location data)"},"lastLocationUpdate":{"type":"string","format":"date-time","nullable":true,"description":"Timestamp of last location update"}}}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/family/subscription":{"post":{"tags":["Family Management"],"summary":"Create family subscription","description":"Create a new family subscription for the authenticated user with the specified tariff plan.","security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateFamilySubscriptionRequest"},"example":{"tariffId":"123e4567-e89b-12d3-a456-426614174000","paymentMethod":"card"}}}},"responses":{"201":{"description":"Family subscription created successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Семейная подписка успешно создана"},"data":{"type":"object","properties":{"subscriptionId":{"type":"string","format":"uuid"}}}}}}}},"400":{"description":"Validation error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Неверные данные запроса"},"errors":{"type":"array","items":{"type":"string"}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"404":{"description":"Tariff plan not found","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Тариф не найден"}}}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/family/data":{"get":{"tags":["Family Management"],"summary":"Get complete family data","description":"Get complete family data including primary user information and all family members.\nReturns the current user's role (primary or member) within the family subscription.\nIf the user has no active family subscription, returns empty data with member role.\n","security":[{"BearerAuth":[]}],"responses":{"200":{"description":"Family data retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"object","properties":{"primaryUser":{"type":"object","nullable":true,"properties":{"id":{"type":"string","format":"uuid"},"firstName":{"type":"string"},"lastName":{"type":"string"},"email":{"type":"string"},"phone":{"type":"string"},"role":{"type":"string"}}},"familyMembers":{"type":"array","items":{"$ref":"#/components/schemas/FamilyMember"}},"currentUserRole":{"type":"string","enum":["primary","member"],"description":"Role of the authenticated user in the family subscription"}}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/family/members":{"get":{"tags":["Family Management"],"summary":"Get family members","description":"Retrieve all family members for the authenticated user's family subscription. Returns an empty array if the user has no active subscription.","security":[{"BearerAuth":[]}],"responses":{"200":{"description":"Family members retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"array","items":{"$ref":"#/components/schemas/FamilyMember"}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"500":{"$ref":"#/components/responses/InternalServerError"}}},"post":{"tags":["Family Management"],"summary":"Add family member","description":"Add a new family member to the authenticated user's family subscription.\nThe user must have an active family subscription. The member is identified\nby email or phone number. If the user is not found and emailOrPhone is an email,\na new client account is auto-created with a generated password. The new user\nreceives a welcome email with credentials and app download links.\nSubject to family_members quota check.\n\nA phone number resolves however it is written: the full digit string is\nmatched first, then the trailing nine subscriber digits, so\n`+996222181806`, `996222181806` and `0222181806` all find the same\naccount. When two accounts share those nine digits and the number was\nnot given in full, the request is refused with\n`PHONE_IDENTIFIER_AMBIGUOUS` rather than one being picked.\n\nOptional free-text fields (`firstName`, `lastName`, `phone`,\n`medicalConditions`, `allergies`, `medications`) accept an empty string\nand treat it as omitted, so a client may post its blank form fields\nas `\"\"`.\n","security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AddFamilyMemberRequest"},"example":{"emailOrPhone":"family@example.com","relationship":"spouse","isMinor":false,"canMakeCalls":true,"requiresParentNotification":false,"emergencyContactPriority":1}}}},"responses":{"201":{"description":"Family member added successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Член семьи успешно добавлен"},"data":{"type":"object","properties":{"familyMemberId":{"type":"string","format":"uuid"}}}}}}}},"400":{"description":"Validation error, no active subscription, or an attempt to add\nyourself (`CANNOT_ADD_YOURSELF_AS_FAMILY_MEMBER`). A validation\nfailure lists every offending field under `errors`.\n","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Нет активной семейной подписки"},"code":{"type":"string","example":"CANNOT_ADD_YOURSELF_AS_FAMILY_MEMBER"},"errors":{"type":"array","description":"Present only for a request-body validation failure.","items":{"type":"string"}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Quota exceeded, or the subscription belongs to another user (`ACCESS_DENIED`)"},"404":{"description":"The invitee has no account and cannot be auto-registered because a\nphone number was given instead of an email\n(`FAMILY_MEMBER_TARGET_NOT_FOUND`), or the subscription does not\nexist (`SUBSCRIPTION_NOT_FOUND`).\n","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Пользователь не найден. Для автоматической регистрации укажите email адрес"},"code":{"type":"string","example":"FAMILY_MEMBER_TARGET_NOT_FOUND"}}}}}},"409":{"description":"Already a member of this family (`USER_ALREADY_FAMILY_MEMBER`), the\ntariff's member limit is reached (`FAMILY_MEMBER_LIMIT_EXCEEDED`),\nthe phone matches several accounts (`PHONE_IDENTIFIER_AMBIGUOUS`),\nor the phone given for a new account already belongs to someone\nelse (`PHONE_ALREADY_EXISTS`).\n","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Пользователь уже является членом семьи"},"code":{"type":"string","example":"USER_ALREADY_FAMILY_MEMBER"}}}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/family/members/{familyMemberId}":{"put":{"tags":["Family Management"],"summary":"Update family member","description":"Update an existing family member's details. Only the primary subscriber\n(or an admin/dispatcher) can update family members.\n\nEvery field is optional and an empty string counts as omitted, so\nposting `\"\"` for a name leaves it unchanged rather than failing — the\ncolumn rejects an empty value. A body that carries no effective change\nanswers 422 `NO_FIELDS_TO_UPDATE`.\n","security":[{"BearerAuth":[]}],"parameters":[{"name":"familyMemberId","in":"path","required":true,"description":"Family member ID","schema":{"type":"string","format":"uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateFamilyMemberRequest"},"example":{"relationship":"child","isMinor":true,"canMakeCalls":true,"requiresParentNotification":true,"emergencyContactPriority":2,"medicalConditions":"Asthma","allergies":"Peanuts"}}}},"responses":{"200":{"description":"Family member updated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Член семьи успешно обновлен"},"data":{"type":"object","properties":{"familyMemberId":{"type":"string","format":"uuid"}}}}}}}},"400":{"description":"Validation error or missing family member ID","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Неверные данные запроса"},"errors":{"type":"array","items":{"type":"string"}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"The family member belongs to another subscriber (`ACCESS_DENIED`)"},"404":{"description":"Family member not found","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Family member not found"}}}}}},"422":{"description":"The body carried no field to update (`NO_FIELDS_TO_UPDATE`)"},"500":{"$ref":"#/components/responses/InternalServerError"}}},"delete":{"tags":["Family Management"],"summary":"Remove family member","description":"Remove a family member from the subscription. Only the primary subscriber can remove members. Decrements the family_members quota after successful removal.","security":[{"BearerAuth":[]}],"parameters":[{"name":"familyMemberId","in":"path","required":true,"description":"Family member ID","schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Family member removed successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Член семьи успешно удален"}}}}}},"400":{"description":"Family member ID is required","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"ID члена семьи обязателен"}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"404":{"description":"Family member not found","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Family member not found"}}}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/family/emergency-call":{"post":{"tags":["Family Management"],"summary":"Create family emergency call","description":"Create an emergency call on behalf of a family member. The user must have an active\nfamily subscription and be a registered family member. Calls from minors are specially\nhandled with parent notifications.\n","security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateFamilyEmergencyCallRequest"},"example":{"description":"Medical emergency at home","coordinates":{"lat":42.8746,"lng":74.5698},"address":"Bishkek, Toktogul St 45, Apt 12"}}}},"responses":{"201":{"description":"Family emergency call created successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Звонок в экстренную службу создан успешно"},"data":{"type":"object","properties":{"callId":{"type":"string","format":"uuid"}}}}}}}},"400":{"description":"Validation error, no active subscription, or user is not a family member","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","examples":{"noSubscription":{"value":"Нет активной семейной подписки"},"notMember":{"value":"Пользователь не является членом семьи"}}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/geocode":{"get":{"summary":"Forward geocode address to coordinates","description":"Converts a human-readable address string into geographic coordinates (lat/lng) and a normalized formatted address. The Google API key is kept server-side — clients never need to embed it.","tags":["Geocoding"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"query","name":"address","required":true,"schema":{"type":"string","minLength":2},"description":"The address string to geocode (in Russian or Latin)","example":"ул. Чуй 100, Бишкек"}],"responses":{"200":{"description":"Geocoding result — either coordinates or a not-found indicator","content":{"application/json":{"schema":{"oneOf":[{"type":"object","description":"Address found","properties":{"success":{"type":"boolean","example":true},"data":{"type":"object","required":["lat","lng","formattedAddress"],"properties":{"lat":{"type":"number","example":42.87},"lng":{"type":"number","example":74.57},"formattedAddress":{"type":"string","example":"ул. Чуй 100, Бишкек"}}}}},{"type":"object","description":"Address not found","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Адрес не найден"}}}]}}}},"400":{"description":"Validation error — address param missing or too short"},"401":{"description":"Authentication required"}}}},"/health":{"get":{"summary":"Health check endpoint","description":"Check the health status of the API server. This endpoint does not require authentication and can be used by load balancers, monitoring tools, and deployment pipelines to verify the server is running.","tags":["Health"],"responses":{"200":{"description":"Server is healthy and running","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HealthCheckResponse"}}}}}}},"/api/invoices":{"post":{"summary":"Create a new invoice","description":"Create an invoice for a completed call (dispatchers/admins only)","tags":["Invoices"],"security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateInvoiceRequest"}}}},"responses":{"201":{"description":"Invoice created successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/Invoice"}}}}}},"400":{"description":"Validation failed or call not completed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidationError"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"Insufficient permissions","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForbiddenError"}}}},"409":{"description":"Invoice already exists for this call","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ConflictError"}}}}}},"get":{"summary":"Get invoices","description":"Get paginated list of invoices with filtering","tags":["Invoices"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"query","name":"page","schema":{"type":"integer","minimum":1,"default":1},"description":"Page number for pagination"},{"in":"query","name":"limit","schema":{"type":"integer","minimum":1,"maximum":100,"default":20},"description":"Number of items per page"},{"in":"query","name":"status","schema":{"type":"string","enum":["pending","paid","overdue","cancelled"]},"description":"Filter by invoice status (can be array)"},{"in":"query","name":"clientId","schema":{"type":"string","format":"uuid"},"description":"Filter by client ID (admins/dispatchers only)"},{"in":"query","name":"paymentMethod","schema":{"type":"string","enum":["cash","card","bank_transfer","mobile_payment","crypto"]},"description":"Filter by payment method"},{"in":"query","name":"startDate","schema":{"type":"string","format":"date-time"},"description":"Filter invoices created after this date"},{"in":"query","name":"endDate","schema":{"type":"string","format":"date-time"},"description":"Filter invoices created before this date"},{"in":"query","name":"overdue","schema":{"type":"boolean"},"description":"Filter only overdue invoices"}],"responses":{"200":{"description":"Invoices retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/PaginatedInvoices"}}}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}}}}},"/api/invoices/overdue":{"get":{"summary":"Get overdue invoices","description":"Get paginated list of overdue invoices (dispatchers/admins only)","tags":["Invoices"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"query","name":"page","schema":{"type":"integer","minimum":1,"default":1},"description":"Page number for pagination"},{"in":"query","name":"limit","schema":{"type":"integer","minimum":1,"maximum":100,"default":20},"description":"Number of items per page"}],"responses":{"200":{"description":"Overdue invoices retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/PaginatedInvoices"}}}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"Insufficient permissions","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForbiddenError"}}}}}}},"/api/invoices/stats":{"get":{"summary":"Get invoice statistics","description":"Get invoice statistics and analytics (dispatchers/admins only)","tags":["Invoices"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"query","name":"startDate","schema":{"type":"string","format":"date-time"},"description":"Filter invoices created after this date"},{"in":"query","name":"endDate","schema":{"type":"string","format":"date-time"},"description":"Filter invoices created before this date"},{"in":"query","name":"clientId","schema":{"type":"string","format":"uuid"},"description":"Filter by specific client"}],"responses":{"200":{"description":"Invoice statistics retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/InvoiceStats"}}}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"Insufficient permissions","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForbiddenError"}}}}}}},"/api/invoices/{id}":{"get":{"summary":"Get invoice by ID","description":"Get a specific invoice by its ID","tags":["Invoices"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"},"description":"Invoice ID"}],"responses":{"200":{"description":"Invoice retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/InvoiceWithDetails"}}}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"Access denied (clients can only see their own invoices)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForbiddenError"}}}},"404":{"description":"Invoice not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/NotFoundError"}}}}}},"put":{"summary":"Update invoice","description":"Update an invoice (dispatchers/admins only)","tags":["Invoices"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"},"description":"Invoice ID"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateInvoiceRequest"}}}},"responses":{"200":{"description":"Invoice updated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/InvoiceWithDetails"}}}}}},"400":{"description":"Validation failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidationError"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"Insufficient permissions","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForbiddenError"}}}},"404":{"description":"Invoice not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/NotFoundError"}}}}}},"delete":{"summary":"Delete invoice","description":"Delete an invoice (admins only, cannot delete paid invoices)","tags":["Invoices"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"},"description":"Invoice ID"}],"responses":{"200":{"description":"Invoice deleted successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Invoice deleted successfully"}}}}}},"400":{"description":"Cannot delete paid invoice","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidationError"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"Insufficient permissions","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForbiddenError"}}}},"404":{"description":"Invoice not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/NotFoundError"}}}}}}},"/api/invoices/{id}/pay":{"post":{"summary":"Pay invoice","description":"Mark an invoice as paid","tags":["Invoices"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"},"description":"Invoice ID"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/PayInvoiceRequest"}}}},"responses":{"200":{"description":"Invoice paid successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/InvoiceWithDetails"},"message":{"type":"string","example":"Invoice paid successfully"}}}}}},"400":{"description":"Validation failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidationError"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"Access denied (clients can only pay their own invoices)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForbiddenError"}}}},"404":{"description":"Invoice not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/NotFoundError"}}}},"409":{"description":"Invoice already paid or cancelled","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ConflictError"}}}}}}},"/api/invoices/{id}/cancel":{"post":{"summary":"Cancel invoice","description":"Cancel an invoice (dispatchers/admins only, cannot cancel paid invoices)","tags":["Invoices"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"},"description":"Invoice ID"}],"responses":{"200":{"description":"Invoice cancelled successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Invoice cancelled successfully"}}}}}},"400":{"description":"Cannot cancel paid invoice","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidationError"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"403":{"description":"Insufficient permissions","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForbiddenError"}}}},"404":{"description":"Invoice not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/NotFoundError"}}}}}}},"/api/notifications":{"get":{"summary":"Get user notifications","description":"Without `page` param: returns unread notifications only (legacy, camelCase fields).\nWith `page` param: returns all notifications paginated (snake_case fields, used by mobile apps).\n","tags":["Notifications"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"query","name":"page","schema":{"type":"integer","minimum":1},"description":"Page number (enables paginated mode)"},{"in":"query","name":"limit","schema":{"type":"integer","minimum":1,"maximum":100,"default":20},"description":"Items per page"}],"responses":{"200":{"description":"List of notifications","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"object","properties":{"notifications":{"type":"array","items":{"$ref":"#/components/schemas/NotificationData"}},"total":{"type":"integer","example":42},"page":{"type":"integer","example":1},"limit":{"type":"integer","example":20},"hasMore":{"type":"boolean","example":true}}}}}}}},"401":{"description":"Unauthorized - invalid or missing JWT token","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Unauthorized"}}}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Internal server error"}}}}}}}},"post":{"summary":"Create a new notification (Admin/Dispatcher only)","description":"Create and send a notification to a specific user. Only admins and dispatchers can create notifications.","tags":["Notifications"],"security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateNotificationRequest"}}}},"responses":{"201":{"description":"Notification created successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Notification created successfully"},"data":{"type":"object","properties":{"notificationId":{"type":"string","format":"uuid","description":"Created notification ID"}}}}}}}},"400":{"description":"Validation error - invalid request data","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Invalid request data"},"errors":{"type":"array","items":{"type":"string"},"example":["\"userId\" is required","\"type\" must be one of [call, assignment, status, message, alert, system]"]}}}}}},"401":{"description":"Unauthorized - invalid or missing JWT token","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Unauthorized"}}}}}},"403":{"description":"Forbidden - only admins and dispatchers can create notifications","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Access denied. Only admins and dispatchers can create notifications."}}}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Internal server error"}}}}}}}}},"/api/notifications/{notificationId}/read":{"patch":{"summary":"Mark a notification as read","description":"Mark a specific notification as read for the authenticated user","tags":["Notifications"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"notificationId","required":true,"schema":{"type":"string","format":"uuid"},"description":"Notification ID to mark as read"}],"responses":{"200":{"description":"Notification marked as read successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Notification marked as read"}}}}}},"400":{"description":"Bad request - notification ID is required","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Notification ID is required"}}}}}},"401":{"description":"Unauthorized - invalid or missing JWT token","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Unauthorized"}}}}}},"404":{"description":"Notification not found","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Notification not found"}}}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Internal server error"}}}}}}}}},"/api/notifications/read-all":{"patch":{"summary":"Mark all notifications as read","description":"Mark all unread notifications as read for the authenticated user","tags":["Notifications"],"security":[{"BearerAuth":[]}],"responses":{"200":{"description":"All notifications marked as read successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"All notifications marked as read"},"data":{"type":"object","properties":{"markedCount":{"type":"integer","description":"Number of notifications marked as read","example":8}}}}}}}},"401":{"description":"Unauthorized - invalid or missing JWT token","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Unauthorized"}}}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Internal server error"}}}}}}}}},"/api/notifications/preferences":{"get":{"summary":"Get user notification preferences","description":"Retrieve notification preferences for the authenticated user. Returns default preferences if none have been set.","tags":["Notifications"],"security":[{"BearerAuth":[]}],"responses":{"200":{"description":"User notification preferences (or defaults if not set)","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","description":"Present only when returning default preferences","example":"No preferences found, using defaults"},"data":{"$ref":"#/components/schemas/NotificationPreferences"}}}}}},"401":{"description":"Unauthorized - invalid or missing JWT token","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Unauthorized"}}}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Internal server error"}}}}}}}},"put":{"summary":"Update user notification preferences","description":"Update notification preferences for the authenticated user","tags":["Notifications"],"security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/NotificationPreferences"}}}},"responses":{"200":{"description":"Preferences updated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Notification preferences updated successfully"},"data":{"$ref":"#/components/schemas/NotificationPreferences"}}}}}},"400":{"description":"Validation error - invalid request data","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Invalid request data"},"errors":{"type":"array","items":{"type":"string"},"example":["\"emailNotifications\" is required","\"pushNotifications\" is required"]}}}}}},"401":{"description":"Unauthorized - invalid or missing JWT token","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Unauthorized"}}}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Internal server error"}}}}}}}}},"/api/notifications/stats":{"get":{"summary":"Get user notification statistics","description":"Retrieve notification statistics (total, unread, counts by type) for the authenticated user","tags":["Notifications"],"security":[{"BearerAuth":[]}],"responses":{"200":{"description":"User notification statistics","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/NotificationStats"}}}}}},"401":{"description":"Unauthorized - invalid or missing JWT token","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Unauthorized"}}}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Internal server error"}}}}}}}}},"/api/notifications/unsent":{"get":{"summary":"Get unsent notifications (Admin only)","description":"Retrieve a list of notifications that have not yet been sent. Only accessible by admin users.","tags":["Notifications"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"query","name":"limit","schema":{"type":"integer","minimum":1,"maximum":200,"default":50},"description":"Maximum number of notifications to return (1-200)"}],"responses":{"200":{"description":"List of unsent notifications","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"object","properties":{"notifications":{"type":"array","items":{"$ref":"#/components/schemas/NotificationData"}},"count":{"type":"integer","description":"Number of unsent notifications","example":12}}}}}}}},"400":{"description":"Bad request - limit out of range","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Limit must be between 1 and 200"}}}}}},"401":{"description":"Unauthorized - invalid or missing JWT token","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Unauthorized"}}}}}},"403":{"description":"Forbidden - only admins can view unsent notifications","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Access denied. Only admins can view unsent notifications."}}}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Internal server error"}}}}}}}}},"/api/notifications/status/{status}":{"get":{"summary":"Get user notifications by status (sent/unsent)","description":"Retrieve notifications for the authenticated user filtered by sent or unsent status","tags":["Notifications"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"status","required":true,"schema":{"type":"string","enum":["sent","unsent"]},"description":"Notification status filter"},{"in":"query","name":"limit","schema":{"type":"integer","minimum":1,"maximum":100,"default":20},"description":"Maximum number of notifications to return (1-100)"}],"responses":{"200":{"description":"List of notifications filtered by status","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"object","properties":{"notifications":{"type":"array","items":{"$ref":"#/components/schemas/NotificationData"}},"count":{"type":"integer","description":"Number of notifications returned","example":15},"status":{"type":"string","description":"The filter status used","example":"sent"}}}}}}}},"400":{"description":"Bad request - invalid status or limit out of range","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string"}}},"examples":{"invalidStatus":{"value":{"success":false,"message":"Status must be 'sent' or 'unsent'"}},"invalidLimit":{"value":{"success":false,"message":"Limit must be between 1 and 100"}}}}}},"401":{"description":"Unauthorized - invalid or missing JWT token","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Unauthorized"}}}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Internal server error"}}}}}}}}},"/api/notifications/{notificationId}/mark-sent":{"patch":{"summary":"Manually mark notification as sent (Admin only)","description":"Manually mark a specific notification as sent. Only accessible by admin users.","tags":["Notifications"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"notificationId","required":true,"schema":{"type":"string","format":"uuid"},"description":"Notification ID to mark as sent"}],"responses":{"200":{"description":"Notification marked as sent successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Notification marked as sent successfully"}}}}}},"400":{"description":"Bad request - notification ID is required","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Notification ID is required"}}}}}},"401":{"description":"Unauthorized - invalid or missing JWT token","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Unauthorized"}}}}}},"403":{"description":"Forbidden - only admins can mark notifications as sent","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Access denied. Only admins can mark notifications as sent."}}}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Internal server error"}}}}}}}}},"/api/notifications/cleanup":{"delete":{"summary":"Delete expired notifications (Admin only)","description":"Remove expired notifications from the system. Only accessible by admin users.","tags":["Notifications"],"security":[{"BearerAuth":[]}],"responses":{"200":{"description":"Expired notifications deleted successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Expired notifications deleted successfully"},"data":{"type":"object","properties":{"deletedCount":{"type":"integer","description":"Number of deleted notifications","example":42}}}}}}}},"401":{"description":"Unauthorized - invalid or missing JWT token","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Unauthorized"}}}}}},"403":{"description":"Forbidden - only admins can cleanup notifications","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Access denied. Only admins can cleanup notifications."}}}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Internal server error"}}}}}}}}},"/api/otp/generate":{"post":{"summary":"Generate and send OTP code","description":"Generate a new one-time password code and send it via email or SMS. No authentication required. Rate-limited to prevent abuse.","tags":["OTP"],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/GenerateOtpRequest"}}}},"responses":{"200":{"description":"OTP generated and sent successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"OTP код отправлен"}}}}}},"400":{"description":"Validation error - invalid request data","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string"}}}}},"examples":{"missingIdentifier":{"value":{"success":false,"error":{"message":"Email или номер телефона обязателен"}}},"invalidType":{"value":{"success":false,"error":{"message":"Тип должен быть 'email' или 'sms'"}}},"invalidPurpose":{"value":{"success":false,"error":{"message":"Недопустимая цель OTP"}}}}}}},"429":{"description":"Rate limit exceeded - too many OTP requests","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string","example":"Too many requests"}}}}}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string","example":"Internal server error"}}}}}}}}}}},"/api/otp/validate":{"post":{"summary":"Validate OTP code","description":"Validate a previously sent OTP code. No authentication required. The identifier and purpose must match the values used during generation.","tags":["OTP"],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidateOtpRequest"}}}},"responses":{"200":{"description":"OTP validated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"OTP код подтвержден"},"data":{"type":"object","properties":{"verified":{"type":"boolean","description":"Whether the OTP code is valid","example":true}}}}}}}},"400":{"description":"Validation error - invalid OTP code or request data","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string"}}}}},"examples":{"missingIdentifier":{"value":{"success":false,"error":{"message":"Email или номер телефона обязателен"}}},"invalidCodeLength":{"value":{"success":false,"error":{"message":"OTP код должен содержать 6 цифр"}}},"invalidCodePattern":{"value":{"success":false,"error":{"message":"OTP код должен содержать только цифры"}}},"invalidPurpose":{"value":{"success":false,"error":{"message":"Недопустимая цель OTP"}}}}}}},"404":{"description":"OTP not found or expired","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string","example":"OTP not found"}}}}}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string","example":"Internal server error"}}}}}}}}}}},"/api/otp/stats":{"get":{"summary":"Get OTP statistics (Admin/Dispatcher only)","description":"Retrieve statistics about active OTP codes including totals and breakdowns by purpose and delivery type. Only accessible by admin and dispatcher roles.","tags":["OTP"],"security":[{"BearerAuth":[]}],"responses":{"200":{"description":"OTP statistics retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/OtpStats"}}}}}},"401":{"description":"Unauthorized - invalid or missing JWT token","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string","example":"Unauthorized"}}}}}}}},"403":{"description":"Forbidden - insufficient permissions (admin or dispatcher role required)","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string","example":"Недостаточно прав доступа"}}}}}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string","example":"Internal server error"}}}}}}}}}}},"/api/payments/pre-check":{"post":{"summary":"Проверка возможности подписки перед оплатой","tags":["Payments"],"security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["tariffPlanId"],"properties":{"tariffPlanId":{"type":"string","format":"uuid"}}}}}},"responses":{"200":{"description":"Результат проверки","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"object","properties":{"eligible":{"type":"boolean"},"reason":{"type":"string","nullable":true}}}}}}}}}}},"/api/payments/create-subscription-payment":{"post":{"summary":"Создать платеж для подписки","tags":["Payments"],"security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["tariffPlanId"],"properties":{"tariffPlanId":{"type":"string","format":"uuid"},"autoRenewal":{"type":"boolean"},"paymentMethod":{"type":"string","enum":["elqr","card","cash","bank_transfer","mobile_payment"]}}}}}},"responses":{"201":{"description":"Платежная ссылка создана","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/PaymentOrder"},"message":{"type":"string"}}}}}}}}},"/api/payments/create-service-payment":{"post":{"summary":"Создать платеж для услуги","tags":["Payments"],"security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["serviceId"],"properties":{"serviceId":{"type":"string","format":"uuid"}}}}}},"responses":{"201":{"description":"Платежная ссылка создана"}}}},"/api/payments/create-renewal-payment":{"post":{"summary":"Создать платеж для продления подписки","tags":["Payments"],"security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["subscriptionId"],"properties":{"subscriptionId":{"type":"string","format":"uuid"}}}}}},"responses":{"201":{"description":"Платежная ссылка для продления создана"}}}},"/api/payments/status/{externalId}":{"get":{"summary":"Проверить статус платежа по external ID","tags":["Payments"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"externalId","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"Статус платежа","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/PaymentOrder"}}}}}}}}},"/api/payments/my-payments":{"get":{"summary":"Получить историю своих платежей","tags":["Payments"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"query","name":"page","schema":{"type":"integer","default":1}},{"in":"query","name":"limit","schema":{"type":"integer","default":20}}],"responses":{"200":{"description":"Список платежей пользователя"}}}},"/api/payments/stats/summary":{"get":{"summary":"Статистика платежей (Admin/Dispatcher)","tags":["Payments"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"query","name":"startDate","schema":{"type":"string","format":"date-time"}},{"in":"query","name":"endDate","schema":{"type":"string","format":"date-time"}}],"responses":{"200":{"description":"Статистика платежей","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/PaymentStats"}}}}}}}}},"/api/payments":{"get":{"summary":"Получить все платежи (Admin/Dispatcher)","tags":["Payments"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"query","name":"userId","schema":{"type":"string","format":"uuid"}},{"in":"query","name":"status","schema":{"type":"string","enum":["created","pending","payer_debit","payer_debit_successful","processing","completed","canceled","refunded","failed","expired"]}},{"in":"query","name":"orderType","schema":{"type":"string","enum":["subscription","service","renewal"]}},{"in":"query","name":"startDate","schema":{"type":"string","format":"date-time"}},{"in":"query","name":"endDate","schema":{"type":"string","format":"date-time"}},{"in":"query","name":"page","schema":{"type":"integer","default":1}},{"in":"query","name":"limit","schema":{"type":"integer","default":20}}],"responses":{"200":{"description":"Список платежей с пагинацией","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"array","items":{"$ref":"#/components/schemas/PaymentOrder"}},"pagination":{"type":"object","properties":{"page":{"type":"integer"},"limit":{"type":"integer"},"total":{"type":"integer"},"pages":{"type":"integer"}}}}}}}}}}},"/api/payments/{id}":{"get":{"summary":"Получить детали платежа (Admin/Dispatcher)","tags":["Payments"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Детали платежа с историей возвратов","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"allOf":[{"$ref":"#/components/schemas/PaymentOrder"},{"type":"object","properties":{"refunds":{"type":"array","items":{"$ref":"#/components/schemas/RefundOrder"}}}}]}}}}}}}}},"/api/payments/{id}/cancel":{"put":{"summary":"Отменить платеж (Admin/Dispatcher)","tags":["Payments"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Платеж отменен","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/PaymentOrder"},"message":{"type":"string"}}}}}},"404":{"description":"Платеж не найден"},"409":{"description":"Платеж уже в терминальном статусе"}}}},"/api/payments/{id}/approve":{"put":{"summary":"Подтвердить платеж вручную (Admin)","description":"Используется когда клиент оплатил, но вебхук NPay не был получен. Активирует подписку/услугу.","tags":["Payments"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Платеж подтвержден","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/PaymentOrder"},"message":{"type":"string"}}}}}},"404":{"description":"Платеж не найден"},"409":{"description":"Платеж уже в терминальном статусе"}}}},"/api/payments/{id}/refund":{"post":{"summary":"Инициировать возврат платежа (Admin)","tags":["Payments"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["amount","comment"],"properties":{"amount":{"type":"number","description":"Сумма возврата в тыйын"},"comment":{"type":"string","maxLength":500}}}}}},"responses":{"201":{"description":"Возврат инициирован","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/RefundOrder"},"message":{"type":"string"}}}}}}}}},"/api/payments/refunds/{refundId}":{"get":{"summary":"Получить статус возврата (Admin/Dispatcher)","tags":["Payments"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"refundId","required":true,"schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Статус возврата","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/RefundOrder"}}}}}}}}},"/api/payments/webhooks/payment":{"post":{"summary":"NPay webhook для платежей (PUBLIC)","tags":["Payments"],"description":"Публичный эндпоинт для приема вебхуков от NPay. Аутентификация через HMAC-SHA512 подпись.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"description":"Webhook обработан"}}}},"/api/payments/webhooks/refund":{"post":{"summary":"NPay webhook для возвратов (PUBLIC)","tags":["Payments"],"description":"Публичный эндпоинт для приема вебхуков возвратов от NPay. Аутентификация через HMAC-SHA512 подпись.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"description":"Webhook обработан"}}}},"/api/quotas":{"get":{"summary":"Get user's quota status","description":"Retrieve all quota limits and current usage for the authenticated user.\nAdmin/Dispatcher can pass a userId query parameter to view another user's quotas.\n","tags":["Quotas"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"query","name":"userId","schema":{"type":"string","format":"uuid"},"description":"User ID to query quotas for (Admin/Dispatcher only). Defaults to authenticated user."}],"responses":{"200":{"description":"User quota status retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"array","items":{"$ref":"#/components/schemas/UserQuota"}},"inheritedFrom":{"type":"string","format":"uuid","nullable":true,"description":"If present, quotas are inherited from this parent user (family member scenario)"}}}}}},"401":{"description":"Unauthorized"},"403":{"description":"Access denied (non-admin trying to query another user's quotas)"},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string"}}}}}}}}}}},"/api/quotas/check/{quotaType}":{"get":{"summary":"Check specific quota availability","description":"Check whether the authenticated user has available quota for a specific quota type.\nReturns detailed information about the quota status including whether the action is allowed,\nremaining quota, and any warning messages. Automatically sends low-quota or exhausted\nnotifications when thresholds are crossed.\n","tags":["Quotas"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"quotaType","required":true,"schema":{"type":"string","enum":["family_members","legal_entities","connected_objects","corporate_locations","employees","emergency_calls","video_storage_days","concurrent_streams"]},"description":"The type of quota to check"}],"responses":{"200":{"description":"Quota check result","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/QuotaCheckResult"}}}}}},"401":{"description":"Unauthorized"},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string"}}}}}}}}}}},"/api/quotas/history":{"get":{"summary":"Get quota usage history","description":"Retrieve the usage history log for the authenticated user's quotas. Optionally filter by quota type and limit the number of results.","tags":["Quotas"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"query","name":"quotaType","schema":{"type":"string","enum":["family_members","legal_entities","connected_objects","corporate_locations","employees","emergency_calls","video_storage_days","concurrent_streams"]},"description":"Filter history by quota type"},{"in":"query","name":"limit","schema":{"type":"integer","minimum":1,"default":50},"description":"Maximum number of history entries to return"}],"responses":{"200":{"description":"Quota usage history retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"array","items":{"$ref":"#/components/schemas/QuotaUsageHistoryEntry"}}}}}}},"401":{"description":"Unauthorized"},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string"}}}}}}}}}}},"/api/quotas/initialize":{"post":{"summary":"Initialize or refresh user quotas based on subscription","description":"Initialize or refresh quotas based on the active subscription's tariff plan and active services.\nBy default refreshes the authenticated user's own quotas.\nAdmin/Dispatcher can pass `userId` in the body to re-initialize any user's quotas — useful\nfor fixing stuck quota rows without direct database access.\n","tags":["Quotas"],"security":[{"BearerAuth":[]}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"userId":{"type":"string","format":"uuid","description":"Target user ID (Admin/Dispatcher only). Defaults to authenticated user."}}}}}},"responses":{"200":{"description":"Quotas initialized successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Quotas initialized successfully"}}}}}},"401":{"description":"Unauthorized"},"403":{"description":"Non-admin trying to initialize another user's quotas"},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string"}}}}}}}}}}},"/api/ratings":{"get":{"summary":"Get all ratings with filters","description":"Retrieve paginated list of call ratings with optional filtering by brigade, rating range, and date range","tags":["Ratings"],"security":[{"bearerAuth":[]}],"parameters":[{"in":"query","name":"brigadeId","schema":{"type":"string","format":"uuid"},"description":"Filter by brigade ID"},{"in":"query","name":"minRating","schema":{"type":"integer","minimum":1,"maximum":5},"description":"Minimum rating filter"},{"in":"query","name":"maxRating","schema":{"type":"integer","minimum":1,"maximum":5},"description":"Maximum rating filter"},{"in":"query","name":"startDate","schema":{"type":"string","format":"date-time"},"description":"Filter ratings from this date"},{"in":"query","name":"endDate","schema":{"type":"string","format":"date-time"},"description":"Filter ratings until this date"},{"in":"query","name":"page","schema":{"type":"integer","default":1,"minimum":1},"description":"Page number"},{"in":"query","name":"limit","schema":{"type":"integer","default":20,"minimum":1},"description":"Number of items per page"}],"responses":{"200":{"description":"Paginated list of ratings with call details","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"array","items":{"allOf":[{"$ref":"#/components/schemas/CallRating"},{"type":"object","properties":{"call":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"title":{"type":"string"},"address":{"type":"string"},"clientId":{"type":"string","format":"uuid"},"brigadeId":{"type":"string","format":"uuid"},"client":{"type":"object","properties":{"first_name":{"type":"string"},"last_name":{"type":"string"}}},"brigade":{"type":"object","nullable":true,"properties":{"id":{"type":"string","format":"uuid"},"name":{"type":"string"}}}}}}}]}},"pagination":{"type":"object","properties":{"page":{"type":"integer","example":1},"limit":{"type":"integer","example":20},"total":{"type":"integer","example":150},"totalPages":{"type":"integer","example":8}}}}}}}},"401":{"description":"Unauthorized"},"403":{"description":"Admin or dispatcher role required"},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","example":"Ошибка при получении рейтингов"}}}}}}}},"post":{"summary":"Create a rating for a completed call","description":"Allows clients to rate a completed call. Only one rating per call is allowed.","tags":["Ratings"],"security":[{"bearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateRatingRequest"}}}},"responses":{"201":{"description":"Rating created successfully","content":{"application/json":{"schema":{"type":"object","properties":{"message":{"type":"string","example":"Рейтинг успешно создан"},"rating":{"$ref":"#/components/schemas/CallRating"}}}}}},"400":{"description":"Validation error or invalid request","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","example":"Ошибка валидации"},"details":{"type":"array","items":{"type":"string"}}}},"examples":{"validation":{"value":{"error":"Ошибка валидации","details":["rating must be between 1 and 5"]}},"notCompleted":{"value":{"error":"Можно оценить только завершенные вызовы","code":"INVALID_INPUT"}}}}}},"403":{"description":"User is not authorized to rate this call","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","example":"Вы можете оценить только свои вызовы"}}}}}},"404":{"description":"Call not found","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","example":"Вызов не найден"}}}}}},"409":{"description":"Rating already exists for this call","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","example":"Вы уже оценили этот вызов"}}}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","example":"Ошибка при создании рейтинга"}}}}}}}}},"/api/ratings/stats":{"get":{"summary":"Get overall rating statistics","description":"Retrieve aggregated rating statistics including averages, distribution, and sub-category averages","tags":["Ratings"],"security":[{"bearerAuth":[]}],"parameters":[{"in":"query","name":"startDate","schema":{"type":"string","format":"date-time"},"description":"Filter statistics from this date"},{"in":"query","name":"endDate","schema":{"type":"string","format":"date-time"},"description":"Filter statistics until this date"}],"responses":{"200":{"description":"Overall rating statistics","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"object","properties":{"averageRating":{"type":"number","format":"float","example":4.3},"totalRatings":{"type":"integer","example":250},"ratingDistribution":{"type":"object","properties":{"1":{"type":"integer","example":5},"2":{"type":"integer","example":10},"3":{"type":"integer","example":30},"4":{"type":"integer","example":85},"5":{"type":"integer","example":120}}},"averageResponseTimeRating":{"type":"number","format":"float","example":4.1},"averageProfessionalismRating":{"type":"number","format":"float","example":4.5},"averageQualityRating":{"type":"number","format":"float","example":4.4}}}}}}}},"401":{"description":"Unauthorized"},"403":{"description":"Admin or dispatcher role required"},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","example":"Ошибка при получении статистики"}}}}}}}}},"/api/ratings/stats/brigades":{"get":{"summary":"Get rating statistics by brigade","description":"Retrieve rating statistics grouped by brigade, sorted by average rating descending","tags":["Ratings"],"security":[{"bearerAuth":[]}],"parameters":[{"in":"query","name":"startDate","schema":{"type":"string","format":"date-time"},"description":"Filter statistics from this date"},{"in":"query","name":"endDate","schema":{"type":"string","format":"date-time"},"description":"Filter statistics until this date"}],"responses":{"200":{"description":"Rating statistics per brigade","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"array","items":{"type":"object","properties":{"brigadeId":{"type":"string","format":"uuid"},"brigadeName":{"type":"string","example":"Бригада Альфа"},"averageRating":{"type":"number","format":"float","example":4.7},"totalRatings":{"type":"integer","example":45},"completedCalls":{"type":"integer","example":40}}}}}}}}},"401":{"description":"Unauthorized"},"403":{"description":"Admin or dispatcher role required"},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","example":"Ошибка при получении статистики бригад"}}}}}}}}},"/api/ratings/{id}":{"put":{"summary":"Update an existing rating","description":"Allows clients to update their own ratings","tags":["Ratings"],"security":[{"bearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"},"description":"Rating ID"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateRatingRequest"}}}},"responses":{"200":{"description":"Rating updated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"message":{"type":"string","example":"Рейтинг успешно обновлен"},"rating":{"$ref":"#/components/schemas/CallRating"}}}}}},"400":{"description":"Validation error or no data to update","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string"},"details":{"type":"array","items":{"type":"string"}}}},"examples":{"validation":{"value":{"error":"Ошибка валидации","details":["rating must be between 1 and 5"]}},"noData":{"value":{"error":"Нет данных для обновления"}}}}}},"403":{"description":"User is not authorized to update this rating","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","example":"Вы можете изменить только свои оценки"}}}}}},"404":{"description":"Rating not found","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","example":"Рейтинг не найден"}}}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","example":"Ошибка при обновлении рейтинга"}}}}}}}}},"/api/ratings/call/{callId}":{"get":{"summary":"Get rating for a specific call","description":"Retrieve the rating associated with a specific call","tags":["Ratings"],"security":[{"bearerAuth":[]}],"parameters":[{"in":"path","name":"callId","required":true,"schema":{"type":"string","format":"uuid"},"description":"Call ID"}],"responses":{"200":{"description":"Rating retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"rating":{"$ref":"#/components/schemas/CallRating"}}}}}},"400":{"description":"Invalid call ID","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","example":"ID вызова обязателен"}}}}}},"404":{"description":"Rating not found","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","example":"Рейтинг не найден"}}}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","example":"Ошибка при получении рейтинга"}}}}}}}}},"/api/ratings/brigade/{brigadeId}/average":{"get":{"summary":"Get average rating for a brigade","description":"Retrieve average rating and performance metrics for a specific brigade","tags":["Ratings"],"security":[{"bearerAuth":[]}],"parameters":[{"in":"path","name":"brigadeId","required":true,"schema":{"type":"string","format":"uuid"},"description":"Brigade ID"}],"responses":{"200":{"description":"Average rating retrieved successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/BrigadeAverageRating"}}}},"400":{"description":"Invalid brigade ID","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","example":"ID бригады обязателен"}}}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","example":"Ошибка при получении среднего рейтинга"}}}}}}}}},"/api/ratings/client/{clientId}":{"get":{"summary":"Get client's rating history","description":"Retrieve all ratings created by a specific client (paginated). Users can only view their own ratings unless they are admin or dispatcher.","tags":["Ratings"],"security":[{"bearerAuth":[]}],"parameters":[{"in":"path","name":"clientId","required":true,"schema":{"type":"string","format":"uuid"},"description":"Client ID"},{"in":"query","name":"page","schema":{"type":"integer","default":1,"minimum":1},"description":"Page number"},{"in":"query","name":"limit","schema":{"type":"integer","default":20,"minimum":1,"maximum":100},"description":"Number of items per page"}],"responses":{"200":{"description":"Ratings retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"ratings":{"type":"array","items":{"$ref":"#/components/schemas/CallRating"}},"pagination":{"type":"object","properties":{"page":{"type":"integer","example":1},"limit":{"type":"integer","example":20},"total":{"type":"integer","example":45},"totalPages":{"type":"integer","example":3}}}}}}}},"400":{"description":"Invalid client ID","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","example":"ID клиента обязателен"}}}}}},"403":{"description":"User is not authorized to view these ratings","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","example":"Нет доступа к этим данным"}}}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","example":"Ошибка при получении истории рейтингов"}}}}}}}}},"/api/reports/generated":{"get":{"tags":["Reports"],"summary":"Get list of generated reports","description":"Retrieve paginated list of generated reports from reports table with filtering (Admin/Dispatcher only)","security":[{"BearerAuth":[]}],"parameters":[{"name":"type","in":"query","description":"Filter by report type","schema":{"type":"string","enum":["daily","monthly","custom","export"]}},{"name":"status","in":"query","description":"Filter by report status","schema":{"type":"string","enum":["pending","processing","completed","failed"]}},{"name":"startDate","in":"query","description":"Filter by date range start","schema":{"type":"string","format":"date"}},{"name":"endDate","in":"query","description":"Filter by date range end","schema":{"type":"string","format":"date"}},{"name":"generatedBy","in":"query","description":"Filter by user who generated the report","schema":{"type":"string","format":"uuid"}},{"name":"page","in":"query","description":"Page number","schema":{"type":"integer","minimum":1,"default":1}},{"name":"limit","in":"query","description":"Items per page","schema":{"type":"integer","minimum":1,"maximum":100,"default":20}}],"responses":{"200":{"description":"Generated reports list retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"object","properties":{"reports":{"type":"array","items":{"$ref":"#/components/schemas/GeneratedReport"}},"pagination":{"type":"object","properties":{"page":{"type":"integer"},"limit":{"type":"integer"},"total":{"type":"integer"},"totalPages":{"type":"integer"}}}}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Insufficient permissions (Admin/Dispatcher only)"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/reports/generated/{id}":{"get":{"tags":["Reports"],"summary":"Get a specific generated report","description":"Retrieve details of a specific generated report by ID (Admin/Dispatcher only)","security":[{"BearerAuth":[]}],"parameters":[{"name":"id","in":"path","required":true,"description":"Report ID","schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Generated report retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/GeneratedReport"}}}}}},"400":{"description":"Invalid report ID"},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Insufficient permissions (Admin/Dispatcher only)"},"404":{"description":"Report not found"},"500":{"$ref":"#/components/responses/InternalServerError"}}},"delete":{"tags":["Reports"],"summary":"Delete a generated report","description":"Soft delete a generated report (Admin only)","security":[{"BearerAuth":[]}],"parameters":[{"name":"id","in":"path","required":true,"description":"Report ID","schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Report deleted successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"message":{"type":"string"}}}}}},"400":{"description":"Invalid report ID"},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Insufficient permissions (Admin only)"},"404":{"description":"Report not found"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/reports/calls":{"get":{"tags":["Reports"],"summary":"Generate calls report","description":"Generate comprehensive report on calls with filtering options (Admin/Dispatcher only)","security":[{"BearerAuth":[]}],"parameters":[{"name":"startDate","in":"query","description":"Start date for report (ISO format)","schema":{"type":"string","format":"date"}},{"name":"endDate","in":"query","description":"End date for report (ISO format)","schema":{"type":"string","format":"date"}},{"name":"status","in":"query","description":"Filter by call status","schema":{"type":"string","enum":["pending","assigned","en_route","arrived","in_progress","completed","cancelled"]}},{"name":"clientId","in":"query","description":"Filter by client ID","schema":{"type":"string","format":"uuid"}},{"name":"brigadeId","in":"query","description":"Filter by brigade ID","schema":{"type":"string","format":"uuid"}},{"name":"type","in":"query","description":"Filter by call type","schema":{"type":"string","enum":["emergency","scheduled","patrol","maintenance"]}},{"name":"priority","in":"query","description":"Filter by call priority","schema":{"type":"string","enum":["low","medium","high","critical"]}}],"responses":{"200":{"description":"Calls report generated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"object","properties":{"reportType":{"type":"string","example":"calls"},"filters":{"type":"object"},"generatedAt":{"type":"string","format":"date-time"},"data":{"$ref":"#/components/schemas/CallsReportData"}}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Insufficient permissions (Admin/Dispatcher only)"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/reports/users":{"get":{"tags":["Reports"],"summary":"Generate users report","description":"Generate comprehensive report on users and registrations (Admin only)","security":[{"BearerAuth":[]}],"parameters":[{"name":"startDate","in":"query","description":"Start date for report (ISO format)","schema":{"type":"string","format":"date"}},{"name":"endDate","in":"query","description":"End date for report (ISO format)","schema":{"type":"string","format":"date"}}],"responses":{"200":{"description":"Users report generated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"object","properties":{"reportType":{"type":"string","example":"users"},"filters":{"type":"object"},"generatedAt":{"type":"string","format":"date-time"},"data":{"$ref":"#/components/schemas/UsersReportData"}}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Insufficient permissions (Admin only)"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/reports/revenue":{"get":{"tags":["Reports"],"summary":"Generate revenue report","description":"Generate comprehensive revenue and financial report (Admin/Dispatcher only)","security":[{"BearerAuth":[]}],"parameters":[{"name":"startDate","in":"query","description":"Start date for report (ISO format)","schema":{"type":"string","format":"date"}},{"name":"endDate","in":"query","description":"End date for report (ISO format)","schema":{"type":"string","format":"date"}},{"name":"clientId","in":"query","description":"Filter by client ID","schema":{"type":"string","format":"uuid"}},{"name":"brigadeId","in":"query","description":"Filter by brigade ID","schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Revenue report generated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"object","properties":{"reportType":{"type":"string","example":"revenue"},"filters":{"type":"object"},"generatedAt":{"type":"string","format":"date-time"},"data":{"$ref":"#/components/schemas/RevenueReportData"}}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Insufficient permissions (Admin/Dispatcher only)"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/reports/work-schedules":{"get":{"tags":["Reports"],"summary":"Generate work schedules report","description":"Generate comprehensive report on brigade work schedules with start/end documentation (Admin/Dispatcher only)","security":[{"BearerAuth":[]}],"parameters":[{"name":"startDate","in":"query","description":"Start date for report (ISO format)","schema":{"type":"string","format":"date"}},{"name":"endDate","in":"query","description":"End date for report (ISO format)","schema":{"type":"string","format":"date"}},{"name":"status","in":"query","description":"Filter by work schedule status","schema":{"type":"string","enum":["not_started","working","on_break","finished"]}},{"name":"brigadeId","in":"query","description":"Filter by brigade ID","schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Work schedules report generated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"object","properties":{"reportType":{"type":"string","example":"work-schedules"},"filters":{"type":"object"},"generatedAt":{"type":"string","format":"date-time"},"data":{"$ref":"#/components/schemas/WorkSchedulesReportData"}}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Insufficient permissions (Admin/Dispatcher only)"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/reports/summary":{"get":{"tags":["Reports"],"summary":"Generate summary dashboard report","description":"Generate combined summary report with calls, users, and revenue data (Admin/Dispatcher only)","security":[{"BearerAuth":[]}],"parameters":[{"name":"startDate","in":"query","description":"Start date for report (defaults to 30 days ago)","schema":{"type":"string","format":"date"}},{"name":"endDate","in":"query","description":"End date for report (defaults to today)","schema":{"type":"string","format":"date"}}],"responses":{"200":{"description":"Summary report generated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"object","properties":{"reportType":{"type":"string","example":"summary"},"filters":{"type":"object"},"generatedAt":{"type":"string","format":"date-time"},"data":{"type":"object","properties":{"calls":{"$ref":"#/components/schemas/CallsReportData"},"users":{"$ref":"#/components/schemas/UsersReportData"},"revenue":{"$ref":"#/components/schemas/RevenueReportData"}}}}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Insufficient permissions (Admin/Dispatcher only)"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/reports/export":{"post":{"tags":["Reports"],"summary":"Export report data","description":"Export report data in various formats (Admin/Dispatcher only)","security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["reportType"],"properties":{"reportType":{"type":"string","enum":["calls","users","revenue","summary","tariffs","quotas"]},"format":{"type":"string","enum":["json","csv","excel"],"default":"json"},"filters":{"type":"object","properties":{"startDate":{"type":"string","format":"date"},"endDate":{"type":"string","format":"date"},"status":{"type":"string"},"clientId":{"type":"string","format":"uuid"},"brigadeId":{"type":"string","format":"uuid"}}}}},"example":{"reportType":"calls","format":"json","filters":{"startDate":"2024-01-01","endDate":"2024-01-31","status":"completed"}}}}},"responses":{"200":{"description":"Report exported successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"object","properties":{"reportType":{"type":"string"},"format":{"type":"string"},"filters":{"type":"object"},"exportedAt":{"type":"string","format":"date-time"},"data":{"type":"object"}}}}}}}},"400":{"$ref":"#/components/responses/ValidationError"},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Insufficient permissions (Admin/Dispatcher only)"},"500":{"$ref":"#/components/responses/InternalServerError"},"501":{"description":"CSV export not yet implemented"}}}},"/api/routing/route":{"get":{"summary":"Get driving route between two points","description":"Returns road-following route coordinates, distance, and duration between origin and destination using OSRM. Falls back to a straight line if OSRM is unavailable.","tags":["Routing"],"security":[{"bearerAuth":[]}],"parameters":[{"in":"query","name":"originLat","required":true,"schema":{"type":"number","minimum":-90,"maximum":90},"description":"Origin latitude","example":42.8826},{"in":"query","name":"originLng","required":true,"schema":{"type":"number","minimum":-180,"maximum":180},"description":"Origin longitude","example":74.6156},{"in":"query","name":"destLat","required":true,"schema":{"type":"number","minimum":-90,"maximum":90},"description":"Destination latitude","example":42.87},{"in":"query","name":"destLng","required":true,"schema":{"type":"number","minimum":-180,"maximum":180},"description":"Destination longitude","example":74.59}],"responses":{"200":{"description":"Route successfully calculated","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/RouteResult"}}}}}},"400":{"description":"Invalid coordinates"},"401":{"description":"Authentication required"}}}},"/api/service-applications":{"post":{"summary":"Создать заявку на услугу","tags":["Service Applications"],"security":[{"bearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["serviceId"],"properties":{"serviceId":{"type":"string","format":"uuid"}}}}}},"responses":{"201":{"description":"Заявка создана"},"409":{"description":"Заявка уже существует"}}},"get":{"summary":"Список всех заявок (админ/диспетчер)","tags":["Service Applications"],"security":[{"bearerAuth":[]}],"parameters":[{"in":"query","name":"status","schema":{"type":"string","enum":["pending","approved","rejected","cancelled"]}},{"in":"query","name":"userId","schema":{"type":"string","format":"uuid"}},{"in":"query","name":"page","schema":{"type":"integer"}},{"in":"query","name":"limit","schema":{"type":"integer"}}],"responses":{"200":{"description":"Список заявок с пагинацией"}}}},"/api/service-applications/pending-count":{"get":{"summary":"Количество заявок на рассмотрении (админ/диспетчер)","tags":["Service Applications"],"security":[{"bearerAuth":[]}],"responses":{"200":{"description":"Количество pending заявок"}}}},"/api/service-applications/my":{"get":{"summary":"Мои заявки (текущий пользователь)","tags":["Service Applications"],"security":[{"bearerAuth":[]}],"responses":{"200":{"description":"Список собственных заявок"}}}},"/api/service-applications/{id}":{"get":{"summary":"Получить заявку по ID","tags":["Service Applications"],"security":[{"bearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Данные заявки"},"404":{"description":"Заявка не найдена"}}}},"/api/service-applications/{id}/approve":{"patch":{"summary":"Одобрить заявку (админ/диспетчер)","tags":["Service Applications"],"security":[{"bearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"contractNumber":{"type":"string"},"paymentAmount":{"type":"number"},"paymentReference":{"type":"string"},"adminNotes":{"type":"string"}}}}}},"responses":{"200":{"description":"Заявка одобрена, услуга активирована"}}}},"/api/service-applications/{id}/reject":{"patch":{"summary":"Отклонить заявку (админ/диспетчер)","tags":["Service Applications"],"security":[{"bearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["rejectionReason"],"properties":{"rejectionReason":{"type":"string"}}}}}},"responses":{"200":{"description":"Заявка отклонена"}}}},"/api/service-applications/{id}/cancel":{"patch":{"summary":"Отменить свою заявку (только pending)","tags":["Service Applications"],"security":[{"bearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Заявка отменена"},"422":{"description":"Заявку можно отменить только в статусе ожидания"}}}},"/api/service-applications/{id}/payment":{"patch":{"summary":"Обновить информацию об оплате/договоре (админ/диспетчер)","tags":["Service Applications"],"security":[{"bearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"contractNumber":{"type":"string"},"contractSignedAt":{"type":"string","format":"date-time"},"contractFileUrl":{"type":"string"},"paymentConfirmed":{"type":"boolean"},"paymentAmount":{"type":"number"},"paymentDate":{"type":"string","format":"date-time"},"paymentReference":{"type":"string"},"adminNotes":{"type":"string"}}}}}},"responses":{"200":{"description":"Информация обновлена"}}}},"/api/services":{"get":{"summary":"Get all addon services","description":"Retrieve list of addon services with optional filtering","tags":["Services"],"parameters":[{"in":"query","name":"serviceType","schema":{"type":"string","enum":["security_monitoring","fire_alarm","video_surveillance","access_control","intrusion_detection","medical_alert","panic_button","smart_home_integration","mobile_app_access","ambulance","cash_collection","personal_security"]},"description":"Filter by service type"},{"in":"query","name":"isActive","schema":{"type":"boolean"},"description":"Filter by active status"},{"in":"query","name":"isAddon","schema":{"type":"boolean"},"description":"Filter addon services"}],"responses":{"200":{"description":"List of services with quota bonuses","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"name":{"type":"string","example":"video_surveillance_addon"},"display_name":{"type":"string","example":"Видеонаблюдение"},"description":{"type":"string"},"service_type":{"type":"string","enum":["security_monitoring","fire_alarm","video_surveillance","access_control","intrusion_detection","medical_alert","panic_button","smart_home_integration","mobile_app_access","ambulance","cash_collection","personal_security"]},"price":{"type":"number","format":"decimal","example":500},"currency":{"type":"string","example":"KGS"},"billing_period":{"type":"string","enum":["monthly","quarterly","yearly","one_time"]},"is_addon":{"type":"boolean","example":true},"requires_plan":{"type":"boolean","example":false},"is_active":{"type":"boolean","example":true},"quotas":{"type":"array","items":{"type":"object","properties":{"quotaType":{"type":"string","example":"video_storage_days"},"quotaAddition":{"type":"integer","example":30}}}}},"$ref":"#/components/schemas/Service"}}}}}}},"500":{"description":"Internal server error"}}},"post":{"summary":"Create new service","description":"Create a new addon service (Admin only)","tags":["Services"],"security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["name","displayName","serviceType","price","billingPeriod"],"properties":{"name":{"type":"string","example":"video_surveillance_addon"},"displayName":{"type":"string","example":"Видеонаблюдение"},"description":{"type":"string","example":"Extended video surveillance service"},"serviceType":{"type":"string","enum":["security_monitoring","fire_alarm","video_surveillance","access_control","intrusion_detection","medical_alert","panic_button","smart_home_integration","mobile_app_access","ambulance","cash_collection","personal_security"],"example":"video_surveillance"},"price":{"type":"number","example":500},"currency":{"type":"string","example":"KGS","default":"KGS"},"billingPeriod":{"type":"string","enum":["monthly","quarterly","yearly","one_time"],"example":"monthly"},"isAddon":{"type":"boolean","example":true,"default":true},"requiresPlan":{"type":"boolean","example":false,"default":false},"sortOrder":{"type":"integer","example":0,"default":0},"quotas":{"type":"array","items":{"type":"object","required":["quotaType","quotaAddition"],"properties":{"quotaType":{"type":"string","enum":["family_members","legal_entities","connected_objects","corporate_locations","employees","emergency_calls","video_storage_days","concurrent_streams","ambulance_calls","cash_collection_calls","personal_security_calls"],"example":"video_storage_days"},"quotaAddition":{"type":"integer","example":30}}}}}}}}},"responses":{"201":{"description":"Service created"},"400":{"description":"Validation error"},"403":{"description":"Admin access required"},"500":{"description":"Internal server error"}}}},"/api/services/{id}":{"get":{"summary":"Get service by ID","description":"Retrieve a specific service with its quota bonuses","tags":["Services"],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"},"description":"Service ID"}],"responses":{"200":{"description":"Service details","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"name":{"type":"string"},"display_name":{"type":"string"},"service_type":{"type":"string"},"price":{"type":"number"},"quotas":{"type":"array"}}}}}}}},"404":{"description":"Service not found"},"500":{"description":"Internal server error"}}},"put":{"summary":"Update a service","description":"Update an existing addon service (Admin only)","tags":["Services"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"},"description":"Service ID"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"displayName":{"type":"string","minLength":2,"maxLength":150,"example":"Видеонаблюдение Про"},"description":{"type":"string","maxLength":1000,"example":"Extended video surveillance with cloud storage"},"price":{"type":"number","minimum":0,"example":750},"billingPeriod":{"type":"string","enum":["monthly","quarterly","yearly","one_time"],"example":"monthly"},"isAddon":{"type":"boolean","example":true},"requiresPlan":{"type":"boolean","example":false},"isActive":{"type":"boolean","example":true},"sortOrder":{"type":"integer","example":1},"quotas":{"type":"array","items":{"type":"object","required":["quotaType","quotaAddition"],"properties":{"quotaType":{"type":"string","enum":["family_members","legal_entities","connected_objects","corporate_locations","employees","emergency_calls","video_storage_days","concurrent_streams","ambulance_calls","cash_collection_calls","personal_security_calls"],"example":"video_storage_days"},"quotaAddition":{"type":"integer","example":60}}}}}}}}},"responses":{"200":{"description":"Service updated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"name":{"type":"string"},"display_name":{"type":"string"},"description":{"type":"string"},"service_type":{"type":"string"},"price":{"type":"number"},"currency":{"type":"string"},"billing_period":{"type":"string"},"is_addon":{"type":"boolean"},"requires_plan":{"type":"boolean"},"is_active":{"type":"boolean"},"sort_order":{"type":"integer"},"quotas":{"type":"array","items":{"type":"object","properties":{"quotaType":{"type":"string"},"quotaAddition":{"type":"integer"}}}}}}}}}}},"400":{"description":"Validation error"},"403":{"description":"Admin access required"},"404":{"description":"Service not found"},"500":{"description":"Internal server error"}}},"delete":{"summary":"Delete service","description":"Soft delete a service (Admin only)","tags":["Services"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"},"description":"Service ID"}],"responses":{"200":{"description":"Service deleted successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"message":{"type":"string"}}}}}},"403":{"description":"Admin access required"},"404":{"description":"Service not found"},"500":{"description":"Internal server error"}}}},"/api/support-chat/start":{"post":{"tags":["Support Chat"],"summary":"Start a new support conversation","description":"Start a new support conversation. Only clients can start conversations. If the user is a corporate employee, the conversation is shared across the company. If an active or waiting conversation already exists, it is returned instead of creating a new one. An operator (dispatcher or admin) is auto-assigned if available. A system message is automatically sent to the conversation.\n","security":[{"BearerAuth":[]}],"requestBody":{"required":false,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StartConversationRequest"}}}},"responses":{"201":{"description":"Support conversation started (or existing active conversation returned)","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/SupportConversation"}}}}}},"400":{"description":"Validation error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"code":{"type":"string","example":"INVALID_INPUT"},"details":{"type":"array","items":{"type":"string"}}}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Access denied - only clients can start support conversations","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"code":{"type":"string","example":"ACCESS_DENIED"},"message":{"type":"string","example":"Only clients can start support conversations"}}}}}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/support-chat/conversation":{"get":{"tags":["Support Chat"],"summary":"Get or create support conversation for client","description":"Get the client's active or waiting support conversation with full details. If no active conversation exists, a new one is automatically created and returned. Only clients can access this endpoint.\n","security":[{"BearerAuth":[]}],"responses":{"200":{"description":"Support conversation details","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/ConversationWithDetails"}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Access denied - only clients can access support conversations","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"code":{"type":"string","example":"ACCESS_DENIED"},"message":{"type":"string","example":"Only clients can access support conversations"}}}}}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/support-chat/conversations":{"get":{"tags":["Support Chat"],"summary":"Get all support conversations (for operators)","description":"Get a paginated list of all support conversations with client and operator details. Only dispatchers and admins can access this endpoint. Conversations are sorted by last message timestamp (most recent first).\n","security":[{"BearerAuth":[]}],"parameters":[{"in":"query","name":"status","description":"Filter by conversation status","schema":{"type":"string","enum":["active","waiting","closed"]}},{"in":"query","name":"page","description":"Page number","schema":{"type":"integer","minimum":1,"default":1}},{"in":"query","name":"limit","description":"Number of items per page","schema":{"type":"integer","minimum":1,"maximum":100,"default":20}}],"responses":{"200":{"description":"Paginated list of support conversations","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"array","items":{"$ref":"#/components/schemas/ConversationWithDetails"}},"pagination":{"type":"object","properties":{"page":{"type":"integer","example":1},"limit":{"type":"integer","example":20},"total":{"type":"integer","example":45},"pages":{"type":"integer","example":3}}}}}}}},"400":{"description":"Validation error on query parameters","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"code":{"type":"string","example":"VALIDATION_ERROR"},"details":{"type":"array","items":{"type":"string"}}}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Access denied - only dispatchers and admins can access all conversations","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"code":{"type":"string","example":"ACCESS_DENIED"},"message":{"type":"string","example":"Only dispatchers and admins can access all conversations"}}}}}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/support-chat/{conversationId}/messages":{"get":{"tags":["Support Chat"],"summary":"Get messages for support conversation","description":"Get paginated messages for a specific support conversation. Messages are ordered by creation time descending (newest first). User must be either the client or operator of the conversation.\n","security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"conversationId","required":true,"description":"Support conversation ID","schema":{"type":"string","format":"uuid"}},{"in":"query","name":"page","description":"Page number","schema":{"type":"integer","minimum":1,"default":1}},{"in":"query","name":"limit","description":"Number of messages per page","schema":{"type":"integer","minimum":1,"maximum":100,"default":50}}],"responses":{"200":{"description":"Support conversation messages retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"array","items":{"$ref":"#/components/schemas/SupportMessage"}},"pagination":{"type":"object","properties":{"page":{"type":"integer","example":1},"limit":{"type":"integer","example":50},"total":{"type":"integer","example":120},"pages":{"type":"integer","example":3}}}}}}}},"400":{"description":"Validation error on query parameters or missing conversation ID","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"code":{"type":"string","example":"INVALID_INPUT"},"message":{"type":"string","example":"Conversation ID is required"}}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"404":{"description":"Conversation not found or user does not have access","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"code":{"type":"string","example":"CONVERSATION_NOT_FOUND"},"message":{"type":"string","example":"Conversation not found"}}}}}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}},"post":{"tags":["Support Chat"],"summary":"Send message in support conversation","description":"Send a new message in a support conversation. Clients can only send messages in their own conversations. Operators (dispatchers/admins) can send messages in any conversation. Sends real-time Socket.IO notifications to the recipient and push notifications.\n","security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"conversationId","required":true,"description":"Support conversation ID","schema":{"type":"string","format":"uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SendMessageRequest"}}}},"responses":{"201":{"description":"Message sent successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/SupportMessage"}}}}}},"400":{"description":"Validation error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"code":{"type":"string","example":"INVALID_INPUT"},"details":{"type":"array","items":{"type":"string"}}}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Access denied - client can only send messages to own conversations","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"code":{"type":"string","example":"ACCESS_DENIED"},"message":{"type":"string"}}}}}}}},"404":{"description":"Conversation not found","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"code":{"type":"string","example":"CONVERSATION_NOT_FOUND"}}}}}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/support-chat/{conversationId}/read":{"post":{"tags":["Support Chat"],"summary":"Mark messages as read in support conversation","description":"Mark all unread messages from other participants as read in the specified conversation. Only marks messages where the sender is not the current user.\n","security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"conversationId","required":true,"description":"Support conversation ID","schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Messages marked as read","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"object","properties":{"markedCount":{"type":"integer","description":"Number of messages marked as read","example":5}}}}}}}},"400":{"description":"Missing conversation ID","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"code":{"type":"string","example":"INVALID_INPUT"},"message":{"type":"string","example":"Conversation ID is required"}}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/support-chat/{conversationId}/close":{"post":{"tags":["Support Chat"],"summary":"Close support conversation","description":"Close a support conversation. The user must be either the client or operator of the conversation. Sets the conversation status to \"closed\" and records the end time. A system message \"Чат завершен.\" is automatically sent.\n","security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"conversationId","required":true,"description":"Support conversation ID","schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Conversation closed successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Conversation closed successfully"}}}}}},"400":{"description":"Missing conversation ID","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"code":{"type":"string","example":"INVALID_INPUT"},"message":{"type":"string","example":"Conversation ID is required"}}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"404":{"description":"Conversation not found or user does not have access"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/tariff-plans":{"get":{"summary":"Get all tariff plans","tags":["Tariff Plans"],"parameters":[{"in":"query","name":"planType","schema":{"type":"string","enum":["individual","family","corporate"]},"description":"Filter by plan type"},{"in":"query","name":"isActive","schema":{"type":"boolean"},"description":"Filter by active status"},{"in":"query","name":"isFeatured","schema":{"type":"boolean"},"description":"Filter featured plans"}],"responses":{"200":{"description":"List of tariff plans with quotas","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"array","items":{"type":"object"}}}}}}}}},"post":{"summary":"Create new tariff plan","tags":["Tariff Plans"],"security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["name","displayName","price","billingPeriod","planType"],"properties":{"name":{"type":"string","example":"individual_basic"},"displayName":{"type":"string","example":"Базовый"},"description":{"type":"string","example":"Basic plan description"},"price":{"type":"number","example":999},"currency":{"type":"string","example":"KGS","default":"KGS"},"billingPeriod":{"type":"string","enum":["monthly","quarterly","yearly","one_time"],"example":"monthly"},"planType":{"type":"string","enum":["individual","family","corporate"],"example":"individual"},"priorityLevel":{"type":"integer","example":3,"default":3},"responseTimeMinutes":{"type":"integer","example":20,"default":15},"isFeatured":{"type":"boolean","example":false,"default":false},"sortOrder":{"type":"integer","example":0,"default":0},"quotas":{"type":"array","items":{"type":"object","required":["quotaType","quotaLimit"],"properties":{"quotaType":{"type":"string","enum":["family_members","legal_entities","connected_objects","corporate_locations","employees","emergency_calls","video_storage_days","concurrent_streams","ambulance_calls","cash_collection_calls","personal_security_calls"],"example":"family_members"},"quotaLimit":{"type":"integer","example":1},"isHardLimit":{"type":"boolean","example":true,"default":true},"overageAllowed":{"type":"boolean","example":false,"default":false},"overagePrice":{"type":"number","format":"decimal","example":0}}}}}}}}},"responses":{"201":{"description":"Tariff plan created"},"403":{"description":"Admin access required"}}}},"/api/tariff-plans/{id}":{"get":{"summary":"Get tariff plan by ID","tags":["Tariff Plans"],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Tariff plan details"},"404":{"description":"Tariff plan not found"}}},"put":{"summary":"Update tariff plan","tags":["Tariff Plans"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"Tariff plan updated"},"403":{"description":"Admin access required"}}},"delete":{"summary":"Delete tariff plan","tags":["Tariff Plans"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"Tariff plan deleted"},"403":{"description":"Admin access required"}}}},"/api/upload/single":{"post":{"tags":["Upload"],"summary":"Upload a single file","description":"Upload a single file to S3 storage","security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"multipart/form-data":{"schema":{"type":"object","required":["file"],"properties":{"file":{"type":"string","format":"binary","description":"File to upload (max 25MB)"}}}}}},"responses":{"200":{"description":"File uploaded successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"object","properties":{"fileUrl":{"type":"string","format":"uri","example":"https://s3.amazonaws.com/bucket/uploads/file123.jpg"},"fileName":{"type":"string","example":"document.pdf"},"fileSize":{"type":"integer","example":1024000},"mimeType":{"type":"string","example":"application/pdf"},"category":{"type":"string","example":"pdf"},"formattedSize":{"type":"string","example":"1.00 MB"}}}}}}}},"400":{"description":"Invalid file or upload error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string","example":"No file provided"}}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"413":{"description":"File too large"},"415":{"description":"Unsupported file type"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/upload/multiple":{"post":{"tags":["Upload"],"summary":"Upload multiple files","description":"Upload multiple files to S3 storage (max 5 files)","security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"multipart/form-data":{"schema":{"type":"object","required":["files"],"properties":{"files":{"type":"array","items":{"type":"string","format":"binary"},"maxItems":5,"description":"Files to upload (max 5 files, 25MB each)"}}}}}},"responses":{"200":{"description":"Files uploaded successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"object","properties":{"totalFiles":{"type":"integer","example":3},"successful":{"type":"integer","example":2},"failed":{"type":"integer","example":1},"files":{"type":"array","items":{"type":"object","properties":{"success":{"type":"boolean"},"fileUrl":{"type":"string","format":"uri"},"fileName":{"type":"string"},"fileSize":{"type":"integer"},"mimeType":{"type":"string"},"category":{"type":"string"},"formattedSize":{"type":"string"},"error":{"type":"string"}}}}}}}}}}},"400":{"$ref":"#/components/responses/ValidationError"},"401":{"$ref":"#/components/responses/UnauthorizedError"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/upload/avatar":{"post":{"tags":["Upload"],"summary":"Upload user avatar","description":"Upload a profile avatar image (max 10MB, images only)","security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"multipart/form-data":{"schema":{"type":"object","required":["avatar"],"properties":{"avatar":{"type":"string","format":"binary","description":"Avatar image file (JPEG, PNG, WebP - max 10MB)"}}}}}},"responses":{"200":{"description":"Avatar uploaded successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"object","properties":{"avatarUrl":{"type":"string","format":"uri","example":"https://s3.amazonaws.com/bucket/avatars/user123/avatar.jpg"},"fileName":{"type":"string","example":"profile.jpg"},"fileSize":{"type":"integer","example":512000},"formattedSize":{"type":"string","example":"500 KB"}}}}}}}},"400":{"$ref":"#/components/responses/ValidationError"},"401":{"$ref":"#/components/responses/UnauthorizedError"},"415":{"description":"Only image files are allowed for avatars"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/upload/chat/{callId}":{"post":{"tags":["Upload"],"summary":"Upload chat attachment","description":"Upload a file attachment for a specific call chat","security":[{"BearerAuth":[]}],"parameters":[{"name":"callId","in":"path","required":true,"description":"Call ID","schema":{"type":"string","format":"uuid"}}],"requestBody":{"required":true,"content":{"multipart/form-data":{"schema":{"type":"object","required":["attachment"],"properties":{"attachment":{"type":"string","format":"binary","description":"File attachment (max 25MB)"}}}}}},"responses":{"200":{"description":"Chat attachment uploaded successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"object","properties":{"callId":{"type":"string","format":"uuid"},"fileUrl":{"type":"string","format":"uri"},"fileName":{"type":"string"},"fileSize":{"type":"integer"},"mimeType":{"type":"string"},"category":{"type":"string"},"formattedSize":{"type":"string"}}}}}}}},"400":{"$ref":"#/components/responses/ValidationError"},"401":{"$ref":"#/components/responses/UnauthorizedError"},"404":{"description":"Call not found"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/upload/shift-report/{brigadeId}":{"post":{"tags":["Upload"],"summary":"Upload brigade shift report files","description":"Upload multiple files for a brigade shift report (max 5 files, 25MB each)","security":[{"BearerAuth":[]}],"parameters":[{"name":"brigadeId","in":"path","required":true,"description":"Brigade ID","schema":{"type":"string","format":"uuid"}}],"requestBody":{"required":true,"content":{"multipart/form-data":{"schema":{"type":"object","required":["reportFiles","shiftDate"],"properties":{"reportFiles":{"type":"array","items":{"type":"string","format":"binary"},"maxItems":10,"description":"Report files (images, PDFs, text - max 5 files, 25MB each)"},"shiftDate":{"type":"string","format":"date","description":"Shift date in ISO format"}}}}}},"responses":{"200":{"description":"Shift report files uploaded successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"object","properties":{"brigadeId":{"type":"string","format":"uuid"},"shiftDate":{"type":"string","format":"date"},"totalFiles":{"type":"integer"},"successful":{"type":"integer"},"failed":{"type":"integer"},"files":{"type":"array","items":{"type":"object","properties":{"success":{"type":"boolean"},"fileUrl":{"type":"string","format":"uri"},"fileName":{"type":"string"},"fileSize":{"type":"integer"},"mimeType":{"type":"string"},"category":{"type":"string"},"formattedSize":{"type":"string"},"error":{"type":"string"}}}}}}}}}}},"400":{"$ref":"#/components/responses/ValidationError"},"401":{"$ref":"#/components/responses/UnauthorizedError"},"404":{"description":"Brigade not found"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/upload/presigned-url":{"post":{"tags":["Upload"],"summary":"Generate presigned upload URL","description":"Generate a presigned URL for direct file upload to S3","security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["fileName","mimeType"],"properties":{"fileName":{"type":"string","example":"document.pdf"},"mimeType":{"type":"string","example":"application/pdf"},"folder":{"type":"string","default":"uploads","example":"documents"}}},"example":{"fileName":"report.pdf","mimeType":"application/pdf","folder":"reports"}}}},"responses":{"200":{"description":"Presigned URL generated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"object","properties":{"uploadUrl":{"type":"string","format":"uri","description":"Presigned URL for direct upload"},"fileUrl":{"type":"string","format":"uri","description":"Final URL where file will be accessible"},"key":{"type":"string","description":"S3 object key"},"expiresIn":{"type":"integer","example":3600,"description":"URL expiration time in seconds"}}}}}}}},"400":{"$ref":"#/components/responses/ValidationError"},"401":{"$ref":"#/components/responses/UnauthorizedError"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/upload/file":{"delete":{"tags":["Upload"],"summary":"Delete a file","description":"Delete a file from S3 storage","security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["fileUrl"],"properties":{"fileUrl":{"type":"string","format":"uri","example":"https://s3.amazonaws.com/bucket/uploads/file123.jpg"}}}}}},"responses":{"200":{"description":"File deleted successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"message":{"type":"string","example":"File deleted successfully"}}}}}},"400":{"description":"Failed to delete file or invalid URL","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string","example":"Failed to delete file"}}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/upload/metadata":{"get":{"tags":["Upload"],"summary":"Get file metadata","description":"Retrieve metadata information for a file","security":[{"BearerAuth":[]}],"parameters":[{"name":"fileUrl","in":"query","required":true,"description":"File URL to get metadata for","schema":{"type":"string","format":"uri"}}],"responses":{"200":{"description":"File metadata retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"object","properties":{"key":{"type":"string"},"size":{"type":"integer"},"lastModified":{"type":"string","format":"date-time"},"contentType":{"type":"string"},"etag":{"type":"string"}}}}}}}},"400":{"$ref":"#/components/responses/ValidationError"},"401":{"$ref":"#/components/responses/UnauthorizedError"},"404":{"description":"File not found"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/users":{"get":{"tags":["Users"],"summary":"Get all users","description":"Retrieve a paginated list of users with optional filtering (Admin/Dispatcher only)","security":[{"BearerAuth":[]}],"parameters":[{"$ref":"#/components/parameters/PageParam"},{"$ref":"#/components/parameters/LimitParam"},{"$ref":"#/components/parameters/SortParam"},{"name":"role","in":"query","description":"Filter by user role","schema":{"type":"string","enum":["client","dispatcher","brigade_member","admin","operator","cor_duty","cor_management"]}},{"name":"roles","in":"query","description":"Filter by several roles at once, for a page that shows a fixed\nsubset. Repeat the parameter (`roles=admin&roles=client`) or pass\na comma-separated list. Unknown values are ignored; when nothing\nvalid remains the result is unfiltered. `role` takes precedence.\n","explode":true,"schema":{"type":"array","items":{"type":"string","enum":["client","dispatcher","brigade_member","admin","operator","cor_duty","cor_management"]}},"example":["admin","dispatcher","brigade_member","client"]},{"name":"status","in":"query","description":"Filter by user status","schema":{"type":"string","enum":["active","inactive","suspended"]}},{"name":"search","in":"query","description":"Search by name or email","schema":{"type":"string"}}],"responses":{"200":{"description":"Users retrieved successfully","content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/PaginatedResponse"},{"type":"object","properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/User"}}}}]}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Insufficient permissions"},"500":{"$ref":"#/components/responses/InternalServerError"}}},"post":{"tags":["Users"],"summary":"Create a new user","description":"Create a new user account (Admin only)","security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["password","first_name","last_name","role"],"anyOf":[{"required":["email"]},{"required":["phone"]}],"properties":{"email":{"type":"string","format":"email","description":"Optional when a phone number is supplied; at least one identifier is required."},"password":{"type":"string","minLength":6},"first_name":{"type":"string","maxLength":50},"last_name":{"type":"string","maxLength":50},"phone":{"type":"string","pattern":"^\\\\+?[1-9]\\\\d{1,14}$"},"role":{"type":"string","enum":["client","dispatcher","brigade_member","admin","operator","cor_duty","cor_management"]}}},"example":{"email":"newuser@example.com","password":"securepassword123","first_name":"John","last_name":"Doe","phone":"+1234567890","role":"client"}}}},"responses":{"201":{"description":"User created successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/User"}}}}}},"400":{"$ref":"#/components/responses/ValidationError"},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Insufficient permissions"},"409":{"description":"User already exists, or PHONE_ALREADY_EXISTS — the phone number collides with an active account on its trailing nine digits, which is the key login resolves on.\n","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string","example":"User with this email already exists"}}}}}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/users/employees":{"get":{"tags":["Users"],"summary":"Get all employees","description":"Retrieve a paginated list of employees with optional filtering (Admin/Dispatcher only)","security":[{"BearerAuth":[]}],"parameters":[{"$ref":"#/components/parameters/PageParam"},{"$ref":"#/components/parameters/LimitParam"},{"$ref":"#/components/parameters/SortParam"},{"name":"role","in":"query","description":"Filter by user role","schema":{"type":"string","enum":["client","dispatcher","brigade_member","admin","operator","cor_duty","cor_management"]}},{"name":"status","in":"query","description":"Filter by user status","schema":{"type":"string","enum":["active","inactive","suspended"]}},{"name":"search","in":"query","description":"Search by name or email","schema":{"type":"string"}}],"responses":{"200":{"description":"Users retrieved successfully","content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/PaginatedResponse"},{"type":"object","properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/User"}}}}]}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Insufficient permissions"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/users/{id}":{"get":{"tags":["Users"],"summary":"Get user by ID","description":"Retrieve a specific user by their ID","security":[{"BearerAuth":[]}],"parameters":[{"name":"id","in":"path","required":true,"description":"User ID","schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"User retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/User"}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"404":{"$ref":"#/components/responses/NotFoundError"},"500":{"$ref":"#/components/responses/InternalServerError"}}},"put":{"tags":["Users"],"summary":"Update user","description":"Update an existing user (Admin only, or users can update their own profile)","security":[{"BearerAuth":[]}],"parameters":[{"name":"id","in":"path","required":true,"description":"User ID","schema":{"type":"string","format":"uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"first_name":{"type":"string","maxLength":50},"last_name":{"type":"string","maxLength":50},"email":{"type":"string","format":"email","description":"Admin-only. Normalized to lowercase. Use to correct a mistyped/mixed-case login email. Send an empty string to clear it - allowed only while the user keeps a phone number."},"phone":{"type":"string","pattern":"^\\\\+?[1-9]\\\\d{1,14}$"},"role":{"type":"string","enum":["client","dispatcher","brigade_member","admin","operator","cor_duty","cor_management"]},"status":{"type":"string","enum":["active","inactive","suspended"]}}},"example":{"first_name":"John","last_name":"Smith","email":"john.smith@example.com","phone":"+1234567890","status":"active"}}}},"responses":{"200":{"description":"User updated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/User"}}}}}},"400":{"$ref":"#/components/responses/ValidationError"},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Insufficient permissions"},"404":{"$ref":"#/components/responses/NotFoundError"},"500":{"$ref":"#/components/responses/InternalServerError"}}},"delete":{"tags":["Users"],"summary":"Delete user","description":"Delete a user account (Admin only)","security":[{"BearerAuth":[]}],"parameters":[{"name":"id","in":"path","required":true,"description":"User ID","schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"User deleted successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"User deleted successfully"}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Insufficient permissions"},"404":{"$ref":"#/components/responses/NotFoundError"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/users/profile":{"get":{"tags":["Users"],"summary":"Get current user profile","description":"Retrieve the profile of the currently authenticated user with statistics. If user is associated with a legal entity, legalEntityId will be included.","security":[{"BearerAuth":[]}],"responses":{"200":{"description":"Profile retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"email":{"type":"string","format":"email"},"phone":{"type":"string"},"first_name":{"type":"string"},"last_name":{"type":"string"},"role":{"type":"string","enum":["client","dispatcher","admin","brigade_member"]},"status":{"type":"string","enum":["active","inactive","suspended"]},"emailVerified":{"type":"boolean"},"phoneVerified":{"type":"boolean"},"avatar_url":{"type":"string"},"legalEntityId":{"type":"string","format":"uuid","description":"Legal entity ID if user is associated with a company (only present for corporate users)"},"stats":{"type":"object","properties":{"totalCalls":{"type":"integer"},"completedCalls":{"type":"integer"},"activeCalls":{"type":"integer"}}},"createdAt":{"type":"string","format":"date-time"},"updatedAt":{"type":"string","format":"date-time"}}},"example":{"id":"123e4567-e89b-12d3-a456-426614174000","email":"owner@company.com","phone":"+79991234567","first_name":"Иван","last_name":"Петров","role":"client","status":"active","emailVerified":false,"phoneVerified":false,"legalEntityId":"987e6543-e21b-12d3-a456-426614174000","stats":{"totalCalls":15,"completedCalls":12,"activeCalls":3},"createdAt":"2025-12-15T08:00:00.000Z","updatedAt":"2025-12-15T08:00:00.000Z"}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"500":{"$ref":"#/components/responses/InternalServerError"}}},"put":{"tags":["Users"],"summary":"Update current user profile","description":"Update the profile of the currently authenticated user","security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"first_name":{"type":"string","maxLength":50},"last_name":{"type":"string","maxLength":50},"phone":{"type":"string","pattern":"^\\\\+?[1-9]\\\\d{1,14}$"},"avatar_url":{"type":"string","format":"uri","maxLength":500,"description":"URL to user's profile picture"}}},"example":{"first_name":"John","last_name":"Smith","phone":"+1234567890","avatar_url":"https://example.com/avatars/user123.jpg"}}}},"responses":{"200":{"description":"Profile updated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/User"}}}}}},"400":{"$ref":"#/components/responses/ValidationError"},"401":{"$ref":"#/components/responses/UnauthorizedError"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/users/profile/phone":{"post":{"tags":["Users"],"summary":"Set own phone number, proved by SMS OTP","description":"Sets the caller's own phone and marks it verified. The OTP is validated and consumed server-side in this same request, so the client cannot claim a number it does not control.\nRequest an OTP first via POST /api/otp/generate with `type: \"sms\"`, `purpose: \"phone_verification\"` and `identifier` equal to the same phone string sent here.\nRefuses with 409 PHONE_ALREADY_EXISTS when another active account shares the trailing nine subscriber digits — login resolves accounts on that suffix, so a duplicate would lock both accounts out of phone login.\n","security":[{"bearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["phone","otpCode"],"properties":{"phone":{"type":"string","example":"+996555123456"},"otpCode":{"type":"string","example":"123456"}}}}}},"responses":{"200":{"description":"Phone verified and saved"},"400":{"description":"Validation failed, or the code is wrong or expired"},"401":{"description":"Unauthorized"},"409":{"description":"PHONE_ALREADY_EXISTS — another account shares the last nine digits"}}}},"/api/users/profile/avatar":{"post":{"tags":["Users"],"summary":"Upload user avatar","description":"Upload and set avatar URL for the currently authenticated user","security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["avatar_url"],"properties":{"avatar_url":{"type":"string","format":"uri","maxLength":500,"description":"URL to the uploaded avatar image","example":"https://example.com/storage/avatars/user123.jpg"}}},"example":{"avatar_url":"https://example.com/storage/avatars/user123.jpg"}}}},"responses":{"200":{"description":"Avatar updated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/User"},"message":{"type":"string","example":"Avatar updated successfully"}}}}}},"400":{"description":"Validation error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string","example":"Validation failed"},"details":{"type":"array","items":{"type":"object","properties":{"field":{"type":"string","example":"avatar_url"},"message":{"type":"string","example":"Avatar URL must be a valid URL"}}}}}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/users/me":{"delete":{"tags":["Users"],"summary":"Delete own account","description":"Delete the currently authenticated user's account (soft delete - archive). This will cancel all active calls and deactivate connected objects.","security":[{"BearerAuth":[]}],"responses":{"200":{"description":"Account deleted successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Ваш аккаунт успешно удален"}}},"example":{"success":true,"message":"Ваш аккаунт успешно удален"}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"404":{"description":"User not found or already deleted","content":{"application/json":{"schema":{"type":"object","properties":{"code":{"type":"string","example":"USER_NOT_FOUND"},"message":{"type":"string","example":"Пользователь не найден"}}}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/users/{id}/stats":{"get":{"tags":["Users"],"summary":"Get user statistics","description":"Retrieve call statistics for a specific user. Admins and dispatchers can view any user's stats; regular users can only view their own.","security":[{"BearerAuth":[]}],"parameters":[{"name":"id","in":"path","required":true,"description":"User ID","schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"User statistics retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"totalCalls":{"type":"integer","description":"Total number of calls created by the user","example":25},"completedCalls":{"type":"integer","description":"Number of completed calls","example":20},"activeCalls":{"type":"integer","description":"Number of currently active calls (not completed or cancelled)","example":2},"totalSpent":{"type":"number","format":"double","description":"Total amount spent on completed calls","example":15000.5}}},"example":{"totalCalls":25,"completedCalls":20,"activeCalls":2,"totalSpent":15000.5}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"description":"Access denied - cannot view other users' statistics"},"404":{"description":"User not found","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","example":"User not found"}}}}}},"500":{"$ref":"#/components/responses/InternalServerError"}}}},"/api/user-services/my-services":{"get":{"summary":"Get user's active services","tags":["User Services"],"security":[{"BearerAuth":[]}],"responses":{"200":{"description":"List of user's active services","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"array","items":{"$ref":"#/components/schemas/UserService"}}}}}}},"401":{"description":"Unauthorized"}}}},"/api/user-services/purchase":{"post":{"summary":"Purchase an addon service","tags":["User Services"],"security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["serviceId"],"properties":{"serviceId":{"type":"string","format":"uuid"},"paymentMethod":{"type":"string","enum":["elqr","card","cash","bank_transfer","mobile_payment"]},"autoRenewal":{"type":"boolean","default":true}}}}}},"responses":{"201":{"description":"Service purchased successfully"},"400":{"description":"Already has service or requires subscription"},"401":{"description":"Unauthorized"}}}},"/api/user-services/{id}/cancel":{"post":{"summary":"Cancel a service","tags":["User Services"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Service cancelled"},"400":{"description":"Service not found or already cancelled"},"401":{"description":"Unauthorized"}}}},"/api/user-subscriptions":{"get":{"summary":"Get all subscriptions with filters","description":"Retrieve paginated list of all user subscriptions with optional filtering (Admin/Dispatcher only)","tags":["User Subscriptions"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"query","name":"userId","schema":{"type":"string","format":"uuid"},"description":"Filter by user ID"},{"in":"query","name":"tariffPlanId","schema":{"type":"string","format":"uuid"},"description":"Filter by tariff plan ID"},{"in":"query","name":"status","schema":{"type":"string","enum":["active","cancelled","expired","suspended"]},"description":"Filter by subscription status"},{"in":"query","name":"page","schema":{"type":"integer","default":1,"minimum":1},"description":"Page number"},{"in":"query","name":"limit","schema":{"type":"integer","default":20,"minimum":1},"description":"Number of items per page"}],"responses":{"200":{"description":"Paginated list of subscriptions","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"array","items":{"$ref":"#/components/schemas/UserSubscription"}},"pagination":{"type":"object","properties":{"page":{"type":"integer","example":1},"limit":{"type":"integer","example":20},"total":{"type":"integer","example":100},"totalPages":{"type":"integer","example":5}}}}}}}},"401":{"description":"Unauthorized"},"403":{"description":"Admin or dispatcher role required","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string","example":"Access denied"}}}}}}}},"500":{"description":"Internal server error"}}}},"/api/user-subscriptions/user/{userId}":{"get":{"summary":"Get active subscription for a specific user","description":"Returns the user's active subscription, including family member inherited subscriptions. Admin/Dispatcher only.","tags":["User Subscriptions"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"userId","required":true,"schema":{"type":"string","format":"uuid"},"description":"User ID to get subscription for"}],"responses":{"200":{"description":"Active subscription details (null if none)","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"allOf":[{"$ref":"#/components/schemas/UserSubscription"},{"type":"object","properties":{"user_role":{"type":"string","enum":["primary","member"],"description":"Whether user owns subscription or inherits via family"},"family_member_id":{"type":"string","format":"uuid","nullable":true},"relationship":{"type":"string","nullable":true,"description":"Family relationship (child, spouse, parent, sibling, other)"},"primary_user_id":{"type":"string","format":"uuid","nullable":true,"description":"ID of the subscription owner (for family members)"}}}]}}}}}},"401":{"description":"Unauthorized"},"403":{"description":"Admin or dispatcher role required"}}}},"/api/user-subscriptions/my-subscription":{"get":{"summary":"Get current user's active subscription","tags":["User Subscriptions"],"security":[{"BearerAuth":[]}],"responses":{"200":{"description":"Active subscription details","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/UserSubscription"}}}}}},"401":{"description":"Unauthorized"}}}},"/api/user-subscriptions/subscribe":{"post":{"summary":"Subscribe to a tariff plan","tags":["User Subscriptions"],"security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["tariffPlanId"],"properties":{"tariffPlanId":{"type":"string","format":"uuid"},"paymentMethod":{"type":"string","enum":["elqr","card","cash","bank_transfer","mobile_payment"]},"autoRenewal":{"type":"boolean","default":true}}}}}},"responses":{"201":{"description":"Successfully subscribed"},"400":{"description":"Already has active subscription or invalid plan"},"401":{"description":"Unauthorized"}}}},"/api/user-subscriptions/change-plan":{"post":{"summary":"Change tariff plan","description":"Atomically cancels the current subscription and creates a new one with a different tariff plan. Quotas are re-initialized for the new plan.","tags":["User Subscriptions"],"security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["tariffPlanId"],"properties":{"tariffPlanId":{"type":"string","format":"uuid","description":"ID of the new tariff plan to switch to"},"paymentMethod":{"type":"string","enum":["elqr","card","cash","bank_transfer","mobile_payment"],"description":"Payment method for the new subscription"}}}}}},"responses":{"200":{"description":"Tariff plan changed successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/UserSubscription"},"message":{"type":"string","example":"Tariff plan changed successfully"}}}}}},"400":{"description":"No active subscription, same plan selected, or invalid plan"},"401":{"description":"Unauthorized"}}}},"/api/user-subscriptions/cancel":{"post":{"summary":"Cancel current subscription","tags":["User Subscriptions"],"security":[{"BearerAuth":[]}],"responses":{"200":{"description":"Subscription cancelled"},"400":{"description":"No active subscription found"},"401":{"description":"Unauthorized"}}}},"/api/user-subscriptions/{id}/cancel":{"post":{"summary":"Cancel subscription by ID (Admin/Dispatcher only)","description":"Cancel a specific user's active subscription by subscription ID. Only available to admin and dispatcher roles.","tags":["User Subscriptions"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"},"description":"Subscription ID to cancel"}],"responses":{"200":{"description":"Subscription cancelled","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Subscription cancelled successfully"}}}}}},"400":{"description":"No active subscription found with this ID"},"401":{"description":"Unauthorized"},"403":{"description":"Admin or dispatcher role required"}}}},"/api/user-subscriptions/history":{"get":{"summary":"Get subscription history","tags":["User Subscriptions"],"security":[{"BearerAuth":[]}],"responses":{"200":{"description":"List of user's subscriptions","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"array","items":{"$ref":"#/components/schemas/UserSubscription"}}}}}}},"401":{"description":"Unauthorized"}}}},"/api/work/start":{"post":{"summary":"Start work day","description":"Start a new work day for the authenticated user's brigade. Requires the user to be assigned to a brigade.","tags":["Work Schedule"],"security":[{"BearerAuth":[]}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StartWorkRequest"}}}},"responses":{"201":{"description":"Work started successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Работа запущена успешно"},"data":{"type":"object","properties":{"scheduleId":{"type":"string","format":"uuid","description":"Created work schedule ID"}}}}}}}},"400":{"description":"Validation error or user not assigned to brigade","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Пользователь не назначен в бригаду"},"errors":{"type":"array","items":{"type":"string"}}}}}}},"401":{"description":"Unauthorized"},"409":{"description":"Work already started today","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Работа уже начата сегодня"}}}}}},"500":{"description":"Internal server error"}}}},"/api/work/lunch/start":{"post":{"summary":"Start lunch break","description":"Start a lunch break for the authenticated user's brigade. Requires an active work session.","tags":["Work Schedule"],"security":[{"BearerAuth":[]}],"responses":{"200":{"description":"Lunch break started successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Прием обеда запущен успешно"}}}}}},"400":{"description":"User not assigned to brigade","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Пользователь не назначен в бригаду"}}}}}},"401":{"description":"Unauthorized"},"404":{"description":"No active work found","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string"}}}}}},"500":{"description":"Internal server error"}}}},"/api/work/lunch/end":{"post":{"summary":"End lunch break","description":"End the current lunch break for the authenticated user's brigade. Requires an active lunch break.","tags":["Work Schedule"],"security":[{"BearerAuth":[]}],"responses":{"200":{"description":"Lunch break ended successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Прием обеда завершен успешно"}}}}}},"400":{"description":"User not assigned to brigade","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Пользователь не назначен в бригаду"}}}}}},"401":{"description":"Unauthorized"},"404":{"description":"No lunch break found","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string"}}}}}},"500":{"description":"Internal server error"}}}},"/api/work/end":{"post":{"summary":"End work day","description":"End the current work day for the authenticated user's brigade. Requires an active work session.","tags":["Work Schedule"],"security":[{"BearerAuth":[]}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StartWorkRequest"}}}},"responses":{"200":{"description":"Work day ended successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Работа завершена успешно"}}}}}},"400":{"description":"Validation error or user not assigned to brigade","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string"},"errors":{"type":"array","items":{"type":"string"}}}}}}},"401":{"description":"Unauthorized"},"404":{"description":"No active work found","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string"}}}}}},"500":{"description":"Internal server error"}}}},"/api/work/force-close":{"post":{"summary":"Force-close work schedules (Admin/Dispatcher)","description":"Bulk force-close orphaned work schedules stuck in working/on_break status.\nOnly schedules with status 'working' or 'on_break' will be closed.\nUsed to clean up orphaned schedules that were never properly ended.\n","tags":["Work Schedule"],"security":[{"bearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["scheduleIds"],"properties":{"scheduleIds":{"type":"array","items":{"type":"string","format":"uuid"},"minItems":1,"maxItems":50,"description":"Array of work schedule IDs to force-close"}}}}}},"responses":{"200":{"description":"Schedules force-closed successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Принудительно закрыто смен: 3"},"data":{"type":"object","properties":{"closedCount":{"type":"integer","description":"Number of schedules actually closed","example":3}}}}}}}},"400":{"description":"Invalid request data"},"403":{"description":"Insufficient permissions (admin/dispatcher only)"},"500":{"description":"Internal server error"}}}},"/api/work/emergency-exit":{"post":{"summary":"Emergency exit from work","description":"Emergency exit allows employees to immediately terminate their work session in critical situations.\nThis endpoint is designed for scenarios where normal work termination is not possible due to:\n- Medical emergencies requiring immediate evacuation\n- Security threats or dangerous situations at work location\n- Equipment failures that make continued work unsafe\n- Natural disasters or extreme weather conditions\n- Family emergencies requiring immediate departure\n- Vehicle breakdowns in remote locations\n\nUnlike normal work end, emergency exit:\n- Does not require completing normal end-of-day procedures\n- Automatically logs the emergency reason for management review\n- Triggers immediate notifications to supervisors and dispatch\n- Bypasses validation checks that might prevent normal work termination\n- Creates an audit trail for insurance and safety compliance\n","tags":["Work Schedule"],"security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/EmergencyExitRequest"}}}},"responses":{"200":{"description":"Emergency exit completed successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Выход из работы в экстренной ситуации завершен успешно. Сотрудники уведомлены."},"data":{"type":"object","properties":{"emergencyId":{"type":"string","format":"uuid","description":"Emergency exit record ID"},"notificationsSent":{"type":"boolean","description":"Whether emergency notifications were sent"}}}}}}}},"400":{"description":"Validation error or user not assigned to brigade","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string"},"errors":{"type":"array","items":{"type":"string"}}}}}}},"401":{"description":"Unauthorized"},"404":{"description":"No active work found","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string"}}}}}},"500":{"description":"Internal server error"}}}},"/api/work/status":{"get":{"summary":"Get current work status","description":"Returns lightweight work status for the brigade. Use this for quick status checks (e.g., showing StartWorkModal).","tags":["Work Schedule"],"security":[{"BearerAuth":[]}],"responses":{"200":{"description":"Current work status","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/WorkStatus"}}}}}},"400":{"description":"User not assigned to brigade","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Пользователь не назначен в бригаду"}}}}}},"401":{"description":"Unauthorized"},"500":{"description":"Internal server error"}}}},"/api/work/today":{"get":{"summary":"Get today's work schedule","description":"Retrieve the work schedule for the current day for the authenticated user's brigade.","tags":["Work Schedule"],"security":[{"BearerAuth":[]}],"responses":{"200":{"description":"Today's work schedule","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/WorkSchedule"}}}}}},"400":{"description":"User not assigned to brigade","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Пользователь не назначен в бригаду"}}}}}},"401":{"description":"Unauthorized"},"404":{"description":"No work schedule found for today","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Расписание работы для сегодня не найдено"}}}}}},"500":{"description":"Internal server error"}}}},"/api/work/history":{"get":{"summary":"Get work history","description":"Retrieve paginated work history for the authenticated user's brigade.","tags":["Work Schedule"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"query","name":"page","schema":{"type":"integer","minimum":1,"default":1},"description":"Page number"},{"in":"query","name":"limit","schema":{"type":"integer","minimum":1,"maximum":100,"default":30},"description":"Maximum number of records per page"}],"responses":{"200":{"description":"Work history retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"object","properties":{"history":{"type":"array","items":{"$ref":"#/components/schemas/WorkSchedule"}},"pagination":{"type":"object","properties":{"page":{"type":"integer","example":1},"limit":{"type":"integer","example":30},"total":{"type":"integer","example":120},"totalPages":{"type":"integer","example":4}}}}}}}}}},"400":{"description":"User not assigned to brigade","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Пользователь не назначен в бригаду"}}}}}},"401":{"description":"Unauthorized"},"500":{"description":"Internal server error"}}}},"/api/work/all":{"get":{"summary":"Get all work schedules with user details (Admin/Dispatcher only)","description":"Retrieve paginated list of all work schedules with user, brigade, and car details. Restricted to admin and dispatcher roles.","tags":["Work Schedule"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"query","name":"page","schema":{"type":"integer","minimum":1,"default":1},"description":"Page number"},{"in":"query","name":"limit","schema":{"type":"integer","minimum":1,"maximum":100,"default":20},"description":"Number of items per page"},{"in":"query","name":"startDate","schema":{"type":"string","format":"date"},"description":"Filter by start date (YYYY-MM-DD)"},{"in":"query","name":"endDate","schema":{"type":"string","format":"date"},"description":"Filter by end date (YYYY-MM-DD)"},{"in":"query","name":"status","schema":{"type":"string","enum":["not_started","working","on_break","finished"]},"description":"Filter by work status"},{"in":"query","name":"brigadeId","schema":{"type":"string","format":"uuid"},"description":"Filter by brigade ID"},{"in":"query","name":"userId","schema":{"type":"string","format":"uuid"},"description":"Filter by user ID"},{"in":"query","name":"search","schema":{"type":"string","maxLength":255},"description":"Search by user name, email, or brigade name"}],"responses":{"200":{"description":"Work schedules retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"array","items":{"$ref":"#/components/schemas/WorkScheduleDetailed"}},"pagination":{"type":"object","properties":{"page":{"type":"integer","example":1},"limit":{"type":"integer","example":20},"total":{"type":"integer","example":150},"pages":{"type":"integer","example":8}}}}}}}},"400":{"description":"Invalid query parameters","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Неверные параметры запроса"},"errors":{"type":"array","items":{"type":"string"}}}}}}},"401":{"description":"Unauthorized"},"403":{"description":"Insufficient permissions (Admin/Dispatcher only)","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string"}}}}}},"500":{"description":"Internal server error"}}}},"/api/work":{"post":{"summary":"Unified work action endpoint (start or end work)","description":"A single endpoint that handles both starting and ending a work day based on the `type` field in the request body. Returns 201 for start actions and 200 for end actions.","tags":["Work Schedule"],"security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/WorkActionRequest"}}}},"responses":{"200":{"description":"Work ended successfully (type=end)","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Работа завершена успешно"}}}}}},"201":{"description":"Work started successfully (type=start)","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Работа запущена успешно"},"data":{"type":"object","properties":{"scheduleId":{"type":"string","format":"uuid","description":"Created schedule ID (only for start action)"}}}}}}}},"400":{"description":"Validation error or user not assigned to brigade","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string"},"errors":{"type":"array","items":{"type":"string"}}}}}}},"401":{"description":"Unauthorized"},"404":{"description":"No active work found (for end action)","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string"}}}}}},"409":{"description":"Work already started today (for start action)","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string"}}}}}},"500":{"description":"Internal server error"}}}},"/api/work/emergency-exits":{"get":{"summary":"Get all emergency exits (Admin/Dispatcher only)","description":"Retrieve paginated list of emergency exit records with brigade and user details. Restricted to admin and dispatcher roles.","tags":["Work Schedule"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"query","name":"page","schema":{"type":"integer","minimum":1,"default":1},"description":"Page number"},{"in":"query","name":"limit","schema":{"type":"integer","minimum":1,"maximum":100,"default":20},"description":"Number of items per page"},{"in":"query","name":"brigadeId","schema":{"type":"string","format":"uuid"},"description":"Filter by brigade ID"},{"in":"query","name":"userId","schema":{"type":"string","format":"uuid"},"description":"Filter by user ID"},{"in":"query","name":"reason","schema":{"type":"string","enum":["medical_emergency","security_threat","equipment_failure","natural_disaster","family_emergency","vehicle_breakdown","other"]},"description":"Filter by emergency exit reason"},{"in":"query","name":"resolved","schema":{"type":"boolean"},"description":"Filter by resolution status"},{"in":"query","name":"startDate","schema":{"type":"string","format":"date"},"description":"Filter by start date"},{"in":"query","name":"endDate","schema":{"type":"string","format":"date"},"description":"Filter by end date"}],"responses":{"200":{"description":"Emergency exits retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"array","items":{"$ref":"#/components/schemas/EmergencyExitRecord"}},"pagination":{"type":"object","properties":{"page":{"type":"integer","example":1},"limit":{"type":"integer","example":20},"total":{"type":"integer","example":5},"pages":{"type":"integer","example":1}}}}}}}},"400":{"description":"Invalid query parameters","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Неверные параметры запроса"},"errors":{"type":"array","items":{"type":"string"}}}}}}},"401":{"description":"Unauthorized"},"403":{"description":"Insufficient permissions (Admin/Dispatcher only)","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string"}}}}}},"500":{"description":"Internal server error"}}}},"/api/work/emergency-exits/{id}/resolve":{"patch":{"summary":"Resolve an emergency exit (Admin/Dispatcher only)","description":"Mark an emergency exit as resolved with optional resolution notes. Restricted to admin and dispatcher roles.","tags":["Work Schedule"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"},"description":"Emergency exit ID"}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ResolveEmergencyExitRequest"}}}},"responses":{"200":{"description":"Emergency exit resolved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Экстренный выход разрешён"},"data":{"type":"object","description":"Resolved emergency exit record"}}}}}},"400":{"description":"Invalid emergency exit ID or validation error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string"}}}}}},"401":{"description":"Unauthorized"},"403":{"description":"Insufficient permissions (Admin/Dispatcher only)","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string"}}}}}},"404":{"description":"Emergency exit not found or already resolved","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string"}}}}}},"500":{"description":"Internal server error"}}}},"/api/work/emergency-exits/unresolved/count":{"get":{"summary":"Get count of unresolved emergency exits (Admin/Dispatcher only)","description":"Returns the total count of unresolved emergency exits. Useful for dashboard badges and alerts.","tags":["Work Schedule"],"security":[{"BearerAuth":[]}],"responses":{"200":{"description":"Count retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"object","properties":{"count":{"type":"integer","example":3,"description":"Number of unresolved emergency exits"}}}}}}}},"401":{"description":"Unauthorized"},"500":{"description":"Internal server error"}}}},"/api/work/{id}":{"get":{"summary":"Get a single work schedule by ID (Admin/Dispatcher only)","description":"Retrieve a detailed work schedule record by its ID, including user, brigade, and car information. Restricted to admin and dispatcher roles.","tags":["Work Schedule"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"},"description":"Work schedule ID"}],"responses":{"200":{"description":"Work schedule retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/WorkScheduleDetailed"}}}}}},"400":{"description":"Invalid work schedule ID","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Неверный ID рабочей смены"}}}}}},"401":{"description":"Unauthorized"},"403":{"description":"Insufficient permissions (Admin/Dispatcher only)","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string"}}}}}},"404":{"description":"Work schedule not found","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Рабочая смена не найдена"}}}}}},"500":{"description":"Internal server error"}}}},"/api/zones":{"get":{"summary":"Get all zones","tags":["Zones"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"query","name":"page","schema":{"type":"integer","minimum":1,"default":1},"description":"Page number"},{"in":"query","name":"limit","schema":{"type":"integer","minimum":1,"maximum":100,"default":20},"description":"Number of zones per page"},{"in":"query","name":"isActive","schema":{"type":"boolean"},"description":"Filter by active status"},{"in":"query","name":"search","schema":{"type":"string"},"description":"Search in zone name and description"}],"responses":{"200":{"description":"List of zones retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"array","items":{"$ref":"#/components/schemas/ZoneWithStats"}},"pagination":{"type":"object","properties":{"page":{"type":"integer","minimum":1},"limit":{"type":"integer","minimum":1,"maximum":100},"total":{"type":"integer","minimum":0},"pages":{"type":"integer","minimum":0}}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"$ref":"#/components/responses/ForbiddenError"},"500":{"$ref":"#/components/responses/InternalServerError"}}},"post":{"summary":"Create a new zone","tags":["Zones"],"security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateZoneRequest"}}}},"responses":{"201":{"description":"Zone created successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/Zone"}}}}}},"400":{"$ref":"#/components/responses/ValidationError"},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"$ref":"#/components/responses/ForbiddenError"}}}},"/api/zones/{id}":{"get":{"summary":"Get zone by ID","tags":["Zones"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"},"description":"Zone ID"}],"responses":{"200":{"description":"Zone retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/ZoneWithStats"}}}}}},"400":{"$ref":"#/components/responses/ValidationError"},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"$ref":"#/components/responses/ForbiddenError"},"404":{"$ref":"#/components/responses/NotFoundError"}}},"put":{"summary":"Update zone","tags":["Zones"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"},"description":"Zone ID"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateZoneRequest"}}}},"responses":{"200":{"description":"Zone updated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/Zone"}}}}}},"400":{"$ref":"#/components/responses/ValidationError"},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"$ref":"#/components/responses/ForbiddenError"},"404":{"$ref":"#/components/responses/NotFoundError"}}},"delete":{"summary":"Delete zone","tags":["Zones"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"},"description":"Zone ID"}],"responses":{"200":{"description":"Zone deleted successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Zone deleted successfully"}}}}}},"400":{"$ref":"#/components/responses/ValidationError"},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"$ref":"#/components/responses/ForbiddenError"},"404":{"$ref":"#/components/responses/NotFoundError"},"422":{"description":"Zone has dependencies","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"code":{"type":"string","example":"ZONE_HAS_DEPENDENCIES"},"message":{"type":"string","example":"Cannot delete zone that has associated brigades or tariffs"}}}}}}}}}}},"/api/zones/find/point":{"get":{"summary":"Find zone containing a point","tags":["Zones"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"query","name":"lat","required":true,"schema":{"type":"number","minimum":-90,"maximum":90},"description":"Latitude","example":42.8746},{"in":"query","name":"lng","required":true,"schema":{"type":"number","minimum":-180,"maximum":180},"description":"Longitude","example":74.5898}],"responses":{"200":{"description":"Zone search result","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/PointInZoneResult"}}}}}},"400":{"$ref":"#/components/responses/ValidationError"},"401":{"$ref":"#/components/responses/UnauthorizedError"}}}},"/api/zones/find/area":{"get":{"summary":"Get zones in bounding box area","tags":["Zones"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"query","name":"north","required":true,"schema":{"type":"number","minimum":-90,"maximum":90},"description":"Northern boundary latitude","example":42.88},{"in":"query","name":"south","required":true,"schema":{"type":"number","minimum":-90,"maximum":90},"description":"Southern boundary latitude","example":42.87},{"in":"query","name":"east","required":true,"schema":{"type":"number","minimum":-180,"maximum":180},"description":"Eastern boundary longitude","example":74.6},{"in":"query","name":"west","required":true,"schema":{"type":"number","minimum":-180,"maximum":180},"description":"Western boundary longitude","example":74.58}],"responses":{"200":{"description":"Zones in area retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"array","items":{"$ref":"#/components/schemas/Zone"}}}}}}},"400":{"$ref":"#/components/responses/ValidationError"},"401":{"$ref":"#/components/responses/UnauthorizedError"}}}},"/api/cor/alerts/my-active":{"get":{"summary":"Get the calling operator's own active alert with brigade response info (or null)","tags":["COR Alerts"],"security":[{"BearerAuth":[]}],"responses":{"200":{"description":"Active alert with brigade response, or null if no active alert","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"nullable":true,"type":"object","properties":{"id":{"type":"string","format":"uuid"},"status":{"type":"string"},"object_name":{"type":"string"},"response":{"nullable":true,"type":"object","properties":{"callId":{"type":"string","format":"uuid"},"callStatus":{"type":"string"},"brigade":{"nullable":true,"type":"object"}}}}}}}}}}}}},"/api/cor/alerts/active":{"get":{"summary":"Get active alerts with location trails","tags":["COR Alerts"],"security":[{"BearerAuth":[]}],"responses":{"200":{"description":"List of active alerts","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"array","items":{"$ref":"#/components/schemas/CORAlert"}}}}}}}}}},"/api/cor/alerts":{"get":{"summary":"Get alerts with pagination and filters","tags":["COR Alerts"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"query","name":"page","schema":{"type":"integer","default":1}},{"in":"query","name":"limit","schema":{"type":"integer","default":20}},{"in":"query","name":"objectId","schema":{"type":"string","format":"uuid"}},{"in":"query","name":"type","schema":{"type":"string","enum":["panic","overdue_report","geofence_breach","gps_anomaly"]}},{"in":"query","name":"excludeTypes","description":"Comma-separated alert types to exclude (e.g. \"overdue_report\"). Used by the Тревоги action queue to hide non-actionable rows.","schema":{"type":"string","example":"overdue_report"}},{"in":"query","name":"status","schema":{"type":"string","enum":["active","acknowledged","resolved","false_alarm"]}},{"in":"query","name":"dateFrom","schema":{"type":"string","format":"date-time"}},{"in":"query","name":"dateTo","schema":{"type":"string","format":"date-time"}}],"responses":{"200":{"description":"Paginated list of alerts"}}},"post":{"summary":"Trigger a new alert (panic button). Panic alerts also create an emergency call for brigade dispatch to the COR object location.","tags":["COR Alerts"],"security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TriggerAlertRequest"}}}},"responses":{"201":{"description":"Alert triggered successfully"}}}},"/api/cor/alerts/{id}/response":{"get":{"summary":"Get the brigade dispatched in response to this alert's emergency call","tags":["COR Alerts"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Brigade response info or null if no call created/brigade assigned yet","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"nullable":true,"type":"object","properties":{"callId":{"type":"string","format":"uuid"},"callStatus":{"type":"string"},"brigade":{"nullable":true,"type":"object","properties":{"id":{"type":"string","format":"uuid"},"name":{"type":"string"},"carModel":{"type":"string","nullable":true},"carNumber":{"type":"string","nullable":true},"leaderName":{"type":"string","nullable":true},"leaderPhone":{"type":"string","nullable":true}}}}}}}}}}}}},"/api/cor/alerts/{id}/call-id":{"get":{"summary":"Get the call_id linked to a COR alert (for opening alert chat)","description":"Returns the emergency call UUID linked to this alert, or null if the call has not been created yet (fire-and-forget window). Accessible to operator, cor_duty, cor_management, admin.","tags":["COR Alerts"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Call ID (or null if not yet created)","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"object","properties":{"callId":{"type":"string","format":"uuid","nullable":true}}}}}}}},"404":{"description":"Alert not found"}}}},"/api/cor/alerts/{id}":{"get":{"summary":"Get a single alert with location trail","tags":["COR Alerts"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Alert details"}}}},"/api/cor/alerts/{id}/location":{"post":{"summary":"Track GPS location during active alert","tags":["COR Alerts"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["latitude","longitude"],"properties":{"latitude":{"type":"number"},"longitude":{"type":"number"},"accuracy":{"type":"number"}}}}}},"responses":{"200":{"description":"Location tracked"}}}},"/api/cor/alerts/{id}/acknowledge":{"post":{"summary":"Acknowledge an alert","tags":["COR Alerts"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Alert acknowledged"}}}},"/api/cor/alerts/{id}/resolve":{"post":{"summary":"Resolve an alert","tags":["COR Alerts"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"resolutionNote":{"type":"string"}}}}}},"responses":{"200":{"description":"Alert resolved"}}}},"/api/cor/alerts/{id}/false-alarm":{"post":{"summary":"Mark alert as false alarm","tags":["COR Alerts"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"resolutionNote":{"type":"string"}}}}}},"responses":{"200":{"description":"Alert marked as false alarm"}}}},"/api/cor/broadcast":{"post":{"summary":"Send an emergency broadcast message to all duty supervisors","description":"Sends a push notification + socket event to all active cor_duty and cor_management\nusers. The object is resolved automatically from the caller's active shift.\nThe caller must have an active shift or a 400 error is returned.\n","tags":["COR Broadcast"],"security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BroadcastMessageRequest"},"examples":{"power_outage":{"summary":"Report power outage","value":{"messageType":"power_outage"}},"custom":{"summary":"Custom message","value":{"messageType":"other","customMessage":"Посторонний автомобиль на территории"}}}}}},"responses":{"200":{"description":"Message sent successfully to all duty supervisors","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Сообщение отправлено дежурным"},"data":{"type":"object","properties":{"messageText":{"type":"string","description":"The resolved Russian message text that was sent","example":"Отключение электричества"}}}}}}}},"400":{"description":"Validation error or no active shift","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"error":{"type":"object","properties":{"message":{"type":"string","example":"Нет активной смены. Заступите на смену для отправки сообщения."}}}}}}}},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden — role not allowed"}}}},"/api/cor/coverage/shifts":{"get":{"tags":["COR Coverage"],"summary":"Shift coverage for a night","description":"Every active object for the chosen night, including objects where no shift was opened — those are the rows supervision exists to catch. A night runs from the object's report_start_time on the given date to its report_end_time, normally on the following day. With no date, the night currently in progress is used. Problem objects (late, absent) sort first. Requires admin, cor_duty or cor_management.\n","security":[{"bearerAuth":[]}],"parameters":[{"in":"query","name":"date","schema":{"type":"string","pattern":"^\\\\d{4}-\\\\d{2}-\\\\d{2}$"},"description":"Night-shift date (Bishkek local). Defaults to the current night."},{"in":"query","name":"objectId","schema":{"type":"string","format":"uuid"}},{"in":"query","name":"region","schema":{"type":"string"}},{"in":"query","name":"status","schema":{"type":"string","enum":["on_shift","late","absent","expected","completed"]}},{"in":"query","name":"problemsOnly","schema":{"type":"boolean"},"description":"Only late and absent objects."}],"responses":{"200":{"description":"Coverage rows and totals","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"object","properties":{"date":{"type":"string"},"objects":{"type":"array","items":{"$ref":"#/components/schemas/CORCoverageRow"}},"summary":{"type":"object","description":"Counts across all objects, before status/problem filtering.","properties":{"total":{"type":"integer"},"on_shift":{"type":"integer"},"late":{"type":"integer"},"absent":{"type":"integer"},"expected":{"type":"integer"},"completed":{"type":"integer"}}}}}}}}}},"400":{"$ref":"#/components/responses/ValidationError"},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"$ref":"#/components/responses/ForbiddenError"}}}},"/api/cor/coverage/reports":{"get":{"tags":["COR Coverage"],"summary":"Doklad matrix for a night","description":"Object x slot grid of dokladi (22:00, 00:00, 02:00, 04:00, 06:00 by default), with a per-slot summary. Slots come from each object's own configuration rather than from stored schedule rows, so an object with no shift — and a slot that expired before the operator arrived — still appears.\nRows are ordered worst first: objects with a missed doklad or no shift at all, then by how many slots they failed, then late, then pending, then compliant, and alphabetically within each group. Matches the ordering of /api/cor/coverage/shifts. Requires admin, cor_duty or cor_management.\n","security":[{"bearerAuth":[]}],"parameters":[{"in":"query","name":"date","schema":{"type":"string","pattern":"^\\\\d{4}-\\\\d{2}-\\\\d{2}$"}},{"in":"query","name":"objectId","schema":{"type":"string","format":"uuid"}},{"in":"query","name":"region","schema":{"type":"string"}},{"in":"query","name":"slot","schema":{"type":"string","format":"date-time"},"description":"Restrict the grid to a single slot time."},{"in":"query","name":"cellStatus","schema":{"type":"string","enum":["on_time","late","pending","missed","no_shift"]},"description":"Keep only objects having at least one slot with this outcome. Applied after the per-slot summary is computed, so the totals still describe every object. Combine with `slot` to answer \"who missed the 02:00\". Note this is a separate vocabulary from the shift `status` filter on /coverage/shifts.\n"}],"responses":{"200":{"description":"Matrix rows and per-slot totals","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"object","properties":{"date":{"type":"string"},"slots":{"type":"array","items":{"type":"string","format":"date-time"}},"rows":{"type":"array","items":{"type":"object","properties":{"object_id":{"type":"string","format":"uuid"},"object_name":{"type":"string"},"object_type":{"type":"string"},"region":{"type":"string","nullable":true},"staffed":{"type":"boolean","description":"Whether anyone opened a shift on this object that night."},"shift_id":{"type":"string","format":"uuid","nullable":true},"user_id":{"type":"string","format":"uuid","nullable":true},"first_name":{"type":"string","nullable":true},"last_name":{"type":"string","nullable":true},"phone":{"type":"string","nullable":true},"cells":{"type":"array","items":{"$ref":"#/components/schemas/CORReportMatrixCell"}}}}},"summary":{"type":"array","description":"Per-slot totals across every object, unaffected by cellStatus.","items":{"type":"object","properties":{"slot":{"type":"string","format":"date-time"},"expected":{"type":"integer"},"on_time":{"type":"integer"},"late":{"type":"integer"},"pending":{"type":"integer"},"missed":{"type":"integer"},"on_time_percent":{"type":"integer","nullable":true,"description":"Share of settled slots sent on time. Null while every slot is still pending."}}}}}}}}}}},"400":{"$ref":"#/components/responses/ValidationError"},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"$ref":"#/components/responses/ForbiddenError"}}}},"/api/cor/coverage/settings":{"get":{"tags":["COR Coverage"],"summary":"Lateness thresholds","description":"Requires admin, cor_duty or cor_management.","security":[{"bearerAuth":[]}],"responses":{"200":{"description":"Current thresholds","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/CORCoverageSettings"}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"$ref":"#/components/responses/ForbiddenError"}}},"put":{"tags":["COR Coverage"],"summary":"Update lateness thresholds","description":"Administrator only. At least one field must be supplied.","security":[{"bearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CORCoverageSettings"}}}},"responses":{"200":{"description":"Updated thresholds"},"400":{"$ref":"#/components/responses/ValidationError"},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"$ref":"#/components/responses/ForbiddenError"}}}},"/api/cor/coverage/analytics":{"get":{"tags":["COR Coverage"],"summary":"Discipline analytics over a range of nights","description":"Aggregates doklad and shift discipline across a period, broken down by object and by employee and ranked worst-first. Expected counts are derived from object configuration, not from stored rows, so nights nobody worked still count against the total. A night is attributed by its start date, so a shift opened at 22:40 and a doklad sent at 02:00 belong to the same night. Lateness is recomputed against the current threshold rather than read from the stored is_late flag, so changing the setting re-scores history. Requires admin or cor_management.\n","security":[{"bearerAuth":[]}],"parameters":[{"in":"query","name":"dateFrom","required":true,"schema":{"type":"string","pattern":"^\\\\d{4}-\\\\d{2}-\\\\d{2}$"},"description":"First night in the range, inclusive (Bishkek local)."},{"in":"query","name":"dateTo","required":true,"schema":{"type":"string","pattern":"^\\\\d{4}-\\\\d{2}-\\\\d{2}$"},"description":"Last night in the range, inclusive. Ranges over 366 nights return empty."},{"in":"query","name":"objectId","schema":{"type":"string","format":"uuid"}},{"in":"query","name":"region","schema":{"type":"string"}},{"in":"query","name":"userId","schema":{"type":"string","format":"uuid"}},{"in":"query","name":"slotTime","schema":{"type":"string","pattern":"^([01]\\\\d|2[0-3]):[0-5]\\\\d$"},"description":"A single report time (HH:MM) across every night in range."},{"in":"query","name":"rankBy","schema":{"type":"string","enum":["on_time_percent","missed","late","unopened_shifts"],"default":"on_time_percent"},"description":"Which figure orders the rankings, worst first. Explicit because \"worst object\" is ambiguous — on-time share, missed count and unopened shifts rank differently.\n"}],"responses":{"200":{"description":"Totals and rankings","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"object","properties":{"range":{"type":"object","properties":{"from":{"type":"string"},"to":{"type":"string"},"nights":{"type":"integer"}}},"rankBy":{"type":"string"},"totals":{"type":"object"},"byObject":{"type":"array","items":{"$ref":"#/components/schemas/CORAnalyticsRow"}},"byEmployee":{"type":"array","items":{"$ref":"#/components/schemas/CORAnalyticsRow"}}}}}}}}},"400":{"$ref":"#/components/responses/ValidationError"},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"$ref":"#/components/responses/ForbiddenError"}}}},"/api/cor/coverage/shifts/export":{"get":{"tags":["COR Coverage"],"summary":"Shift coverage for a night as Excel","description":"Same rows and filters as GET /api/cor/coverage/shifts, including the objects where no shift was opened, with the totals appended below the table. Requires admin, cor_duty or cor_management.\n","security":[{"bearerAuth":[]}],"parameters":[{"in":"query","name":"date","schema":{"type":"string","pattern":"^\\\\d{4}-\\\\d{2}-\\\\d{2}$"}},{"in":"query","name":"objectId","schema":{"type":"string","format":"uuid"}},{"in":"query","name":"region","schema":{"type":"string"}},{"in":"query","name":"status","schema":{"type":"string","enum":["on_shift","late","absent","expected","completed"]}},{"in":"query","name":"problemsOnly","schema":{"type":"boolean"}}],"responses":{"200":{"description":"XLSX workbook","content":{"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":{"schema":{"type":"string","format":"binary"}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"$ref":"#/components/responses/ForbiddenError"}}}},"/api/cor/coverage/reports/export":{"get":{"tags":["COR Coverage"],"summary":"Doklad matrix for a night as Excel","description":"Two sheets — the object x slot grid with each cell spelled out in words rather than icons, and the per-slot summary. Same filters as GET /api/cor/coverage/reports. Requires admin, cor_duty or cor_management.\n","security":[{"bearerAuth":[]}],"parameters":[{"in":"query","name":"date","schema":{"type":"string","pattern":"^\\\\d{4}-\\\\d{2}-\\\\d{2}$"}},{"in":"query","name":"objectId","schema":{"type":"string","format":"uuid"}},{"in":"query","name":"region","schema":{"type":"string"}},{"in":"query","name":"slot","schema":{"type":"string","format":"date-time"}},{"in":"query","name":"cellStatus","schema":{"type":"string","enum":["on_time","late","pending","missed","no_shift"]}}],"responses":{"200":{"description":"XLSX workbook","content":{"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":{"schema":{"type":"string","format":"binary"}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"$ref":"#/components/responses/ForbiddenError"}}}},"/api/cor/coverage/analytics/export":{"get":{"tags":["COR Coverage"],"summary":"Analytics as Excel","description":"Three sheets — totals, the object ranking and the employee ranking. Same filters as GET /api/cor/coverage/analytics. Requires admin or cor_management.\n","security":[{"bearerAuth":[]}],"parameters":[{"in":"query","name":"dateFrom","required":true,"schema":{"type":"string","pattern":"^\\\\d{4}-\\\\d{2}-\\\\d{2}$"}},{"in":"query","name":"dateTo","required":true,"schema":{"type":"string","pattern":"^\\\\d{4}-\\\\d{2}-\\\\d{2}$"}},{"in":"query","name":"objectId","schema":{"type":"string","format":"uuid"}},{"in":"query","name":"region","schema":{"type":"string"}},{"in":"query","name":"userId","schema":{"type":"string","format":"uuid"}},{"in":"query","name":"slotTime","schema":{"type":"string"}},{"in":"query","name":"rankBy","schema":{"type":"string","enum":["on_time_percent","missed","late","unopened_shifts"]}}],"responses":{"200":{"description":"XLSX workbook","content":{"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":{"schema":{"type":"string","format":"binary"}}}},"400":{"$ref":"#/components/responses/ValidationError"},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"$ref":"#/components/responses/ForbiddenError"}}}},"/api/cor/dashboard/metrics":{"get":{"summary":"Get real-time dashboard metrics","tags":["COR Dashboard"],"security":[{"BearerAuth":[]}],"responses":{"200":{"description":"Dashboard metrics","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/CORDashboardMetrics"}}}}}}}}},"/api/cor/dashboard/analytics":{"get":{"summary":"Get analytics for a date range","tags":["COR Dashboard"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"query","name":"dateFrom","required":true,"schema":{"type":"string","format":"date-time"}},{"in":"query","name":"dateTo","required":true,"schema":{"type":"string","format":"date-time"}}],"responses":{"200":{"description":"Analytics data","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/CORAnalytics"}}}}}}}}},"/api/cor/dashboard/ratings":{"get":{"summary":"Get employee performance ratings","tags":["COR Dashboard"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"query","name":"dateFrom","schema":{"type":"string","format":"date-time"}},{"in":"query","name":"dateTo","schema":{"type":"string","format":"date-time"}}],"responses":{"200":{"description":"Employee ratings"}}}},"/api/cor/events":{"get":{"tags":["COR Events"],"summary":"Get COR event log","security":[{"BearerAuth":[]}],"parameters":[{"in":"query","name":"userId","schema":{"type":"string","format":"uuid"}},{"in":"query","name":"action","schema":{"type":"string"}},{"in":"query","name":"entityType","schema":{"type":"string"}},{"in":"query","name":"dateFrom","schema":{"type":"string","format":"date-time"}},{"in":"query","name":"dateTo","schema":{"type":"string","format":"date-time"}},{"in":"query","name":"page","schema":{"type":"integer","default":1}},{"in":"query","name":"limit","schema":{"type":"integer","default":20}}],"responses":{"200":{"description":"Event log entries with pagination","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"user_id":{"type":"string","format":"uuid"},"action":{"type":"string"},"entity_type":{"type":"string"},"entity_id":{"type":"string","format":"uuid","nullable":true},"details":{"type":"object"},"ip_address":{"type":"string","nullable":true},"user_agent":{"type":"string","nullable":true},"created_at":{"type":"string","format":"date-time"},"first_name":{"type":"string"},"last_name":{"type":"string"}}}},"pagination":{"type":"object","properties":{"page":{"type":"integer"},"limit":{"type":"integer"},"total":{"type":"integer"},"pages":{"type":"integer"}}}}}}}}}}},"/api/cor/objects":{"get":{"summary":"Get all COR objects","tags":["COR Objects"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"query","name":"page","schema":{"type":"integer","default":1}},{"in":"query","name":"limit","schema":{"type":"integer","default":20}},{"in":"query","name":"type","schema":{"type":"string","enum":["azs","nb","gns","parking","office","other"]}},{"in":"query","name":"isActive","schema":{"type":"boolean"}},{"in":"query","name":"search","schema":{"type":"string"}}],"responses":{"200":{"description":"List of COR objects","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"array","items":{"$ref":"#/components/schemas/CORObject"}},"pagination":{"type":"object","properties":{"page":{"type":"integer"},"limit":{"type":"integer"},"total":{"type":"integer"},"pages":{"type":"integer"}}}}}}}},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"}}},"post":{"summary":"Create a new COR object","tags":["COR Objects"],"security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateCORObjectRequest"}}}},"responses":{"201":{"description":"COR object created","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/CORObject"}}}}}},"400":{"description":"Validation error"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden - admin only"}}}},"/api/cor/objects/my-objects":{"get":{"summary":"Get COR objects bound to the authenticated operator","tags":["COR Objects"],"security":[{"BearerAuth":[]}],"responses":{"200":{"description":"Objects retrieved successfully"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"}}}},"/api/cor/objects/for-user/{userId}":{"get":{"summary":"Get all COR objects bound to a specific user","tags":["COR Objects"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"userId","required":true,"schema":{"type":"string","format":"uuid"},"description":"The user ID to get bound objects for"}],"responses":{"200":{"description":"List of COR objects bound to the user (includes position and is_primary fields)","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"array","items":{"allOf":[{"$ref":"#/components/schemas/CORObject"},{"type":"object","properties":{"position":{"type":"string"},"is_primary":{"type":"boolean"}}}]}}}}}}},"400":{"description":"Invalid ID format"},"403":{"description":"Forbidden - admin only"}}}},"/api/cor/objects/{id}":{"get":{"summary":"Get a COR object by ID","tags":["COR Objects"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"COR object details","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/CORObject"}}}}}},"404":{"description":"Object not found"}}},"put":{"summary":"Update a COR object","tags":["COR Objects"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateCORObjectRequest"}}}},"responses":{"200":{"description":"COR object updated","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/CORObject"}}}}}},"400":{"description":"Validation error"},"404":{"description":"Object not found"}}},"delete":{"summary":"Soft delete a COR object","tags":["COR Objects"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Object deleted"},"404":{"description":"Object not found"}}}},"/api/cor/objects/{id}/checkpoints":{"get":{"summary":"Get checkpoints for a COR object","tags":["COR Objects"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"List of checkpoints","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"array","items":{"$ref":"#/components/schemas/CORCheckpoint"}}}}}}},"404":{"description":"Object not found"}}},"post":{"summary":"Create a checkpoint for a COR object","tags":["COR Objects"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateCheckpointRequest"}}}},"responses":{"201":{"description":"Checkpoint created","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/CORCheckpoint"}}}}}},"400":{"description":"Validation error"},"404":{"description":"Object not found"}}}},"/api/cor/objects/checkpoints/{id}":{"put":{"summary":"Update a checkpoint","tags":["COR Objects"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateCheckpointRequest"}}}},"responses":{"200":{"description":"Checkpoint updated","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/CORCheckpoint"}}}}}},"400":{"description":"Validation error"},"404":{"description":"Checkpoint not found"}}},"delete":{"summary":"Soft delete a checkpoint","tags":["COR Objects"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Checkpoint deleted"},"404":{"description":"Checkpoint not found"}}}},"/api/cor/objects/{id}/users":{"get":{"summary":"Get users bound to a COR object","tags":["COR Objects"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"List of bound users","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"array","items":{"$ref":"#/components/schemas/CORUserObject"}}}}}}},"404":{"description":"Object not found"}}}},"/api/cor/objects/{id}/bind-user":{"post":{"summary":"Bind a user to a COR object","tags":["COR Objects"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BindUserRequest"}}}},"responses":{"201":{"description":"User bound to object","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/CORUserObject"}}}}}},"400":{"description":"Validation error"},"404":{"description":"Object not found"}}}},"/api/cor/objects/{id}/unbind-user/{userId}":{"delete":{"summary":"Unbind a user from a COR object","tags":["COR Objects"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}},{"in":"path","name":"userId","required":true,"schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"User unbound from object"},"404":{"description":"Binding not found"}}}},"/api/cor/patrol/log":{"post":{"summary":"Log a checkpoint visit with photo","tags":["COR Patrol"],"security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["shiftId","checkpointId","photoUrl","latitude","longitude"],"properties":{"shiftId":{"type":"string","format":"uuid"},"checkpointId":{"type":"string","format":"uuid"},"photoUrl":{"type":"string","format":"uri"},"latitude":{"type":"number"},"longitude":{"type":"number"}}}}}},"responses":{"201":{"description":"Checkpoint logged successfully"}}}},"/api/cor/patrol/status/{shiftId}":{"get":{"summary":"Get patrol status for a shift","tags":["COR Patrol"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"shiftId","required":true,"schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Patrol status with checkpoints","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/CORPatrolStatus"}}}}}}}}},"/api/cor/reports":{"post":{"summary":"Submit a new report","tags":["COR Reports"],"security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SubmitReportRequest"}}}},"responses":{"201":{"description":"Report submitted","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/CORReport"}}}}}},"400":{"description":"Validation error"},"422":{"description":"Shift not active or not owned by user"}}},"get":{"summary":"Get reports with pagination and filters","tags":["COR Reports"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"query","name":"page","schema":{"type":"integer","default":1}},{"in":"query","name":"limit","schema":{"type":"integer","default":20}},{"in":"query","name":"objectId","schema":{"type":"string","format":"uuid"}},{"in":"query","name":"userId","schema":{"type":"string","format":"uuid"}},{"in":"query","name":"situation","schema":{"type":"string","enum":["calm","suspicious","emergency"]}},{"in":"query","name":"isLate","schema":{"type":"boolean"}},{"in":"query","name":"dateFrom","schema":{"type":"string","format":"date-time"}},{"in":"query","name":"dateTo","schema":{"type":"string","format":"date-time"}}],"responses":{"200":{"description":"Paginated list of reports","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"array","items":{"$ref":"#/components/schemas/CORReport"}},"pagination":{"type":"object","properties":{"page":{"type":"integer"},"limit":{"type":"integer"},"total":{"type":"integer"},"pages":{"type":"integer"}}}}}}}}}}},"/api/cor/reports/overdue":{"get":{"summary":"Get overdue reports","tags":["COR Reports"],"security":[{"BearerAuth":[]}],"responses":{"200":{"description":"List of overdue report schedules","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"array","items":{"type":"object"}}}}}}}}}},"/api/cor/reports/schedule":{"get":{"summary":"Get report history for operator's active shift","description":"Returns only past slots (scheduled_at <= NOW()) ordered newest first. Each item includes a server-computed date_label for section grouping.","tags":["COR Reports"],"security":[{"BearerAuth":[]}],"responses":{"200":{"description":"Past report slots with date_label for grouping","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"array","items":{"$ref":"#/components/schemas/CORReportSchedule"}}}}}}}}}},"/api/cor/reports/{id}":{"get":{"summary":"Get a single report by ID","tags":["COR Reports"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Report detail","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/CORReport"}}}}}},"403":{"description":"Access denied (operator can only view own reports)"},"404":{"description":"Report not found"}}}},"/api/cor/shifts/start":{"post":{"summary":"Start a new shift","tags":["COR Shifts"],"security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StartShiftRequest"}}}},"responses":{"201":{"description":"Shift started","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/CORShift"}}}}}},"400":{"description":"Validation error"},"403":{"description":"Not bound to object"},"409":{"description":"Active shift already exists"}}}},"/api/cor/shifts/end":{"post":{"summary":"End the active shift","tags":["COR Shifts"],"security":[{"BearerAuth":[]}],"responses":{"200":{"description":"Shift ended","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/CORShift"}}}}}},"404":{"description":"No active shift found"}}}},"/api/cor/shifts/active":{"get":{"summary":"Get the active shift for current operator","tags":["COR Shifts"],"security":[{"BearerAuth":[]}],"responses":{"200":{"description":"Active shift details (null if no active shift)","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/CORShift"}}}}}}}}},"/api/cor/shifts":{"get":{"summary":"Get shifts with pagination and filters","tags":["COR Shifts"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"query","name":"page","schema":{"type":"integer","default":1}},{"in":"query","name":"limit","schema":{"type":"integer","default":20}},{"in":"query","name":"objectId","schema":{"type":"string","format":"uuid"}},{"in":"query","name":"userId","schema":{"type":"string","format":"uuid"}},{"in":"query","name":"status","schema":{"type":"string","enum":["active","completed","abandoned"]}},{"in":"query","name":"dateFrom","schema":{"type":"string","format":"date-time"}},{"in":"query","name":"dateTo","schema":{"type":"string","format":"date-time"}}],"responses":{"200":{"description":"Paginated list of shifts","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"array","items":{"$ref":"#/components/schemas/CORShift"}},"pagination":{"type":"object","properties":{"page":{"type":"integer"},"limit":{"type":"integer"},"total":{"type":"integer"},"pages":{"type":"integer"}}}}}}}}}}},"/api/cor/shifts/{id}":{"get":{"summary":"Get a specific shift by ID","tags":["COR Shifts"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Shift details","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/CORShift"}}}}}},"404":{"description":"Shift not found"}}}},"/api/cor/vehicles/monitoring-summary":{"get":{"tags":["COR Vehicles"],"summary":"Vehicle monitoring summary (cor_duty, cor_management, admin)","description":"Real-time dashboard rollup — active vehicle count, last-24h event counts by type, unacknowledged event count, and the most recent events with vehicle names.","security":[{"BearerAuth":[]}],"responses":{"200":{"description":"Monitoring summary","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"object","properties":{"activeVehicles":{"type":"integer"},"last24h":{"type":"object","additionalProperties":{"type":"integer"},"description":"Event counts keyed by event_type for the last 24h"},"unacknowledged":{"type":"integer"},"recentEvents":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"vehicle_id":{"type":"string","format":"uuid"},"vehicle_name":{"type":"string","nullable":true},"vehicle_plate":{"type":"string","nullable":true},"event_type":{"type":"string"},"latitude":{"type":"number","nullable":true},"longitude":{"type":"number","nullable":true},"speed_kmh":{"type":"number","nullable":true},"details":{"type":"object"},"is_acknowledged":{"type":"boolean"},"created_at":{"type":"string","format":"date-time"}}}}}}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"}}}},"/api/cor/vehicles":{"get":{"tags":["COR Vehicles"],"summary":"Get all vehicles","security":[{"BearerAuth":[]}],"parameters":[{"in":"query","name":"vehicleType","schema":{"type":"string","enum":["fuel_truck","service","other"]}},{"in":"query","name":"isActive","schema":{"type":"boolean"}},{"in":"query","name":"page","schema":{"type":"integer","default":1}},{"in":"query","name":"limit","schema":{"type":"integer","default":20}}],"responses":{"200":{"description":"Vehicles list with pagination"}}},"post":{"tags":["COR Vehicles"],"summary":"Create a vehicle (admin only)","security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["name","plateNumber"],"properties":{"name":{"type":"string"},"plateNumber":{"type":"string"},"gpsTrackerId":{"type":"string"},"vehicleType":{"type":"string","enum":["fuel_truck","service","other"]},"maxSpeedKmh":{"type":"integer"},"maxStopMinutes":{"type":"integer"},"fuelTankCapacityL":{"type":"number"}}}}}},"responses":{"201":{"description":"Vehicle created"}}}},"/api/cor/vehicles/{id}":{"get":{"tags":["COR Vehicles"],"summary":"Get vehicle by ID","security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Vehicle details"}}},"put":{"tags":["COR Vehicles"],"summary":"Update a vehicle (admin only)","security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string"},"plateNumber":{"type":"string"},"gpsTrackerId":{"type":"string"},"vehicleType":{"type":"string"},"maxSpeedKmh":{"type":"integer"},"maxStopMinutes":{"type":"integer"},"fuelTankCapacityL":{"type":"number"},"isActive":{"type":"boolean"}}}}}},"responses":{"200":{"description":"Vehicle updated"}}},"delete":{"tags":["COR Vehicles"],"summary":"Delete a vehicle (admin only)","security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Vehicle deleted"}}}},"/api/cor/vehicles/events":{"get":{"tags":["COR Vehicles"],"summary":"Get vehicle events/anomalies","security":[{"BearerAuth":[]}],"parameters":[{"in":"query","name":"vehicleId","schema":{"type":"string","format":"uuid"}},{"in":"query","name":"eventType","schema":{"type":"string"}},{"in":"query","name":"isAcknowledged","schema":{"type":"boolean"}},{"in":"query","name":"dateFrom","schema":{"type":"string","format":"date-time"}},{"in":"query","name":"dateTo","schema":{"type":"string","format":"date-time"}},{"in":"query","name":"page","schema":{"type":"integer"}},{"in":"query","name":"limit","schema":{"type":"integer"}}],"responses":{"200":{"description":"Vehicle events list"}}}},"/api/cor/vehicles/events/{id}/ack":{"post":{"tags":["COR Vehicles"],"summary":"Acknowledge a vehicle event","security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Event acknowledged"}}}},"/api/cor/vehicles/zones":{"get":{"tags":["COR Vehicles"],"summary":"Get all vehicle zones","security":[{"BearerAuth":[]}],"responses":{"200":{"description":"Vehicle zones list"}}},"post":{"tags":["COR Vehicles"],"summary":"Create a vehicle zone (admin only)","security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["name","zoneType","polygon"],"properties":{"name":{"type":"string"},"zoneType":{"type":"string","enum":["allowed","forbidden"]},"polygon":{"type":"object"}}}}}},"responses":{"201":{"description":"Zone created"}}}},"/api/cor/vehicles/zones/{id}":{"put":{"tags":["COR Vehicles"],"summary":"Update a vehicle zone (admin only)","security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string"},"zoneType":{"type":"string"},"polygon":{"type":"object"},"isActive":{"type":"boolean"}}}}}},"responses":{"200":{"description":"Zone updated"}}},"delete":{"tags":["COR Vehicles"],"summary":"Delete a vehicle zone (admin only)","security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Zone deleted"}}}},"/cor/wialon/login":{"post":{"tags":["COR Wialon"],"summary":"Connect to Wialon with credentials","description":"Authenticates with the Wialon platform and stores the session for subsequent requests. The password is hashed with MD5 before transmission per Wialon API requirements.","security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["username","password"],"properties":{"username":{"type":"string","example":"dispatch_user"},"password":{"type":"string","example":"secret123"}}}}}},"responses":{"200":{"description":"Connection established","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Подключение к Wialon установлено"}}}}}},"400":{"description":"Validation error"},"401":{"description":"Unauthorized (JWT)"},"403":{"description":"Forbidden (insufficient role)"},"502":{"description":"Wialon rejected credentials or is unavailable"}}}},"/cor/wialon/login-token":{"post":{"tags":["COR Wialon"],"summary":"Connect to Wialon using an API token","description":"Authenticates with Wialon via `token/login` (recommended for Wialon Local 2104+).\nThe token is stored with a sentinel prefix so the session can be automatically\nrenewed without requiring a password. Use this instead of `/login` when the\nserver returns error 8 with username/password authentication.\n","security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["token"],"properties":{"token":{"type":"string","minLength":10,"description":"Wialon API token generated in the Wialon user profile","example":"4df678a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7"}}}}}},"responses":{"200":{"description":"Connection established via token","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Подключение к Wialon через токен установлено"}}}}}},"400":{"description":"Validation error (token missing or too short)"},"401":{"description":"Unauthorized (JWT)"},"403":{"description":"Forbidden (insufficient role)"},"502":{"description":"Wialon rejected the token or is unavailable"}}}},"/cor/wialon/status":{"get":{"tags":["COR Wialon"],"summary":"Get current Wialon session status","security":[{"BearerAuth":[]}],"responses":{"200":{"description":"Session status","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"$ref":"#/components/schemas/WialonStatus"}}}}}},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"}}}},"/cor/wialon/units":{"get":{"tags":["COR Wialon"],"summary":"Get all GPS tracking units","description":"Returns all units from Wialon with their current position data (flags 1025 = base info + GPS position).","security":[{"BearerAuth":[]}],"responses":{"200":{"description":"List of units","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"array","items":{"$ref":"#/components/schemas/WialonUnit"}},"total":{"type":"integer"}}}}}},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"502":{"description":"Wialon error"}}}},"/cor/wialon/resources":{"get":{"tags":["COR Wialon"],"summary":"Get Wialon resources with report templates","security":[{"BearerAuth":[]}],"responses":{"200":{"description":"List of resources","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"array","items":{"$ref":"#/components/schemas/WialonResource"}}}}}}},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"502":{"description":"Wialon error"}}}},"/cor/wialon/geofences":{"get":{"tags":["COR Wialon"],"summary":"Get all geofences from Wialon","description":"Fetches all geofences (zones) across all Wialon resources using\n`core/search_items` with flags 4097 (base info + zones). Returns a flat\nlist enriched with geometry type labels, a human-readable centre coordinate,\nand the owning resource name.\n","security":[{"BearerAuth":[]}],"responses":{"200":{"description":"List of geofences","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"array","items":{"$ref":"#/components/schemas/WialonGeofence"}},"total":{"type":"integer","description":"Total number of geofences returned"}}}}}},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"502":{"description":"Wialon error (session expired, connection refused, etc.)"}}}},"/cor/wialon/templates/{resourceId}":{"get":{"tags":["COR Wialon"],"summary":"Get report templates for a resource","security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"resourceId","required":true,"schema":{"type":"integer"},"description":"Wialon resource ID"}],"responses":{"200":{"description":"List of report templates","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"array","items":{"$ref":"#/components/schemas/WialonTemplate"}}}}}}},"400":{"description":"Invalid resourceId"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Resource not found"},"502":{"description":"Wialon error"}}}},"/cor/wialon/reports/generate":{"post":{"tags":["COR Wialon"],"summary":"Generate a system-defined report from raw Wialon GPS data","description":"Fetches raw GPS messages from Wialon via `messages/load_interval` and processes\nthem with our own logic. Supports four report types:\n- **status** — current online/offline status of each unit (no date range needed)\n- **activity** — mileage, trips, moving time per unit for the given period\n- **violations** — speed limit violations per unit for the given period\n- **stops** — parking/stop events per unit for the given period\n\nWarning: can take 10–60 seconds for large date ranges or many units.\n","security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["type","unitIds"],"properties":{"type":{"type":"string","enum":["status","activity","violations","stops"],"description":"Report type: status=текущий статус, activity=активность,\nviolations=превышения скорости, stops=стоянки\n"},"unitIds":{"oneOf":[{"type":"array","items":{"type":"integer"},"minItems":1,"description":"Specific unit IDs to include"},{"type":"string","enum":["all"],"description":"Include all units"}],"description":"Wialon unit IDs to include, or \"all\""},"from":{"type":"integer","description":"Unix timestamp — start of period (required for activity/violations/stops)","example":1746396000},"to":{"type":"integer","description":"Unix timestamp — end of period (required for activity/violations/stops)","example":1746482400},"speedLimit":{"type":"integer","minimum":1,"maximum":300,"default":60,"description":"Speed limit in km/h for violations report"},"minStopMinutes":{"type":"integer","minimum":1,"maximum":1440,"default":5,"description":"Minimum stop duration in minutes for stops report"}}}}}},"responses":{"200":{"description":"Generated report with headers, rows, and summary statistics","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"$ref":"#/components/schemas/GeneratedReport"}}}}}},"400":{"description":"Validation error (missing required fields, invalid type, missing date range)"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden (insufficient role)"},"502":{"description":"Wialon error (session expired, unit not found, etc.)"}}}},"/cor/wialon/reports/export":{"post":{"tags":["COR Wialon"],"summary":"Export data to Excel (.xlsx)","description":"Generates an Excel workbook with the given headers and rows, styled with the SecuriForse brand color. Returns the file as a binary download.","security":[{"BearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["sheetName","headers","rows"],"properties":{"sheetName":{"type":"string","description":"Excel worksheet name","example":"Отчёт по маршрутам"},"headers":{"type":"array","items":{"type":"string"},"description":"Column header labels","example":["Дата","Время начала","Пробег, км"]},"rows":{"type":"array","items":{"type":"array","items":{"type":"string"}},"description":"Data rows (each row is an array of string values)"}}}}}},"responses":{"200":{"description":"Excel file download","content":{"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":{"schema":{"type":"string","format":"binary"}}}},"400":{"description":"Validation error"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"500":{"description":"Excel generation error"}}}},"/cor/wialon/units/{unitId}/track":{"get":{"summary":"Get GPS track for a unit","description":"Fetches raw GPS messages from Wialon for a specific unit over a time range and returns processed track data: route points, stop events, total distance and duration. Default range is the last 8 hours. Can take up to 60 seconds for large ranges.\n","tags":["COR Wialon"],"security":[{"BearerAuth":[]}],"parameters":[{"in":"path","name":"unitId","required":true,"schema":{"type":"integer"},"description":"Wialon unit ID"},{"in":"query","name":"from","schema":{"type":"integer"},"description":"Start time (Unix timestamp). Defaults to now - 8h."},{"in":"query","name":"to","schema":{"type":"integer"},"description":"End time (Unix timestamp). Defaults to now."}],"responses":{"200":{"description":"Track data","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"data":{"type":"object","properties":{"points":{"type":"array","description":"GPS track points","items":{"type":"object","properties":{"lat":{"type":"number"},"lng":{"type":"number"},"speed":{"type":"number","description":"Speed in km/h"},"course":{"type":"number","description":"Heading in degrees (0=north)"},"ts":{"type":"integer","description":"Unix timestamp"}}}},"stops":{"type":"array","description":"Detected stop events (speed=0 for ≥5 min)","items":{"type":"object","properties":{"lat":{"type":"number"},"lng":{"type":"number"},"from":{"type":"string","description":"Stop start time (formatted)"},"to":{"type":"string","description":"Stop end time (formatted)"},"duration":{"type":"string","description":"Stop duration (formatted)"},"index":{"type":"integer","description":"Stop sequence number (1-based)"}}}},"totalDistance":{"type":"number","description":"Total distance in km"},"totalDuration":{"type":"string","description":"Total trip duration (formatted)"}}}}}}}},"400":{"description":"Invalid unit ID or time range"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"500":{"description":"Wialon API error"}}}},"/cor/wialon/sync-vehicles":{"post":{"tags":["COR Wialon"],"summary":"Sync Wialon units into cor_vehicles table","description":"Fetches all active GPS units from Wialon and upserts them into the\n`cor_vehicles` database table. Matching is done by `wialon_unit_id`.\nNew units are inserted; existing units have their `icon_url` updated.\nPlate number conflicts are resolved via ON CONFLICT upsert.\nRequires admin or cor_management role.\n","security":[{"BearerAuth":[]}],"responses":{"200":{"description":"Sync completed successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"data":{"type":"object","properties":{"created":{"type":"integer","description":"Number of new vehicles created","example":3},"updated":{"type":"integer","description":"Number of existing vehicles updated","example":5}}}}}}}},"401":{"description":"Unauthorized (JWT)"},"403":{"description":"Forbidden (insufficient role — requires admin or cor_management)"},"502":{"description":"Wialon API error or session not established"}}}}}}