{"openapi":"3.0.0","info":{"title":"SwilUnify API","description":"B2B Transaction Exchange Platform API documentation for v2 endpoints.","version":"1.0.0"},"servers":[{"url":"http://localhost:4000/api/v2","description":"Local"},{"url":"https://api-test.swilunify.com/api/v2","description":"Testing"},{"url":"https://api.swilunify.com/api/v2","description":"Production"}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"JWT","description":"JWT token obtained from login. Include as 'Bearer {token}' in Authorization header."},"bearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"JWT","description":"Same as BearerAuth"},"ApiKeyAuth":{"type":"apiKey","in":"header","name":"x-api-key","description":"Company API key for server-to-server authentication (ERP integrations)"},"AppKeyAuth":{"type":"apiKey","in":"header","name":"x-app-key","description":"Application key for platform identification"},"BasicAuth":{"type":"http","scheme":"basic","description":"Base64 encoded email:password for login endpoints. Format - 'Basic base64(email:password)'"}},"schemas":{"RegisteredUser":{"type":"object","properties":{"_id":{"type":"string","example":"507f1f77bcf86cd799439011"},"email":{"type":"string","example":"user@example.com"},"userName":{"type":"string","example":"John Doe"},"phone_no":{"type":"string","example":"+919876543210"},"isActive":{"type":"boolean","example":true},"accountStatus":{"type":"string","enum":["PENDING","APPROVED","REJECTED","CLAIMED"],"example":"APPROVED"},"companyName":{"type":"string","example":"ABC Electronics Pvt Ltd"},"gstin":{"type":"string","example":"27AABCU9603R1ZM"},"pan":{"type":"string","example":"AABCU9603R"},"address":{"type":"object"},"actionBy":{"type":"object","properties":{"adminUsername":{"type":"string"},"createdAt":{"type":"string","format":"date-time"}}},"createdAt":{"type":"string","format":"date-time"}}},"AdminStatistics":{"type":"object","properties":{"users":{"type":"object","properties":{"totalUsers":{"type":"integer","example":1500},"activeUsers":{"type":"integer","example":1400},"adminUsers":{"type":"integer","example":1200},"guestUsers":{"type":"integer","example":300}}},"companies":{"type":"object","properties":{"totalCompanies":{"type":"integer","example":1200},"activeCompanies":{"type":"integer","example":1150}}},"ownership":{"type":"object","properties":{"totalOwnershipClaims":{"type":"integer","example":50},"pendingClaims":{"type":"integer","example":10}}}}},"ErrorResponse":{"type":"object","properties":{"success":{"type":"boolean","example":false},"statusCode":{"type":"integer","example":400},"message":{"type":"string","example":"Invalid input data"}}},"ApiKeyResponse":{"type":"object","properties":{"apiKey":{"type":"string","description":"Encrypted API key (store securely)","example":"U2FsdGVkX1+..."},"apiSecret":{"type":"string","description":"API secret hash for verification","example":"a1b2c3d4e5f6..."},"companyId":{"type":"string","example":"507f1f77bcf86cd799439011"},"companyName":{"type":"string","example":"ABC Electronics Pvt Ltd"},"generatedAt":{"type":"string","format":"date-time","example":"2024-01-15T10:30:00Z"}}},"ApiKeyDetails":{"type":"object","properties":{"companyId":{"type":"string","example":"507f1f77bcf86cd799439011"},"companyName":{"type":"string","example":"ABC Electronics Pvt Ltd"},"apiKey":{"type":"string","description":"Masked API key","example":"U2FsdGVk...c3d4"},"fullApiKey":{"type":"string","description":"Full API key (shown once)","example":"U2FsdGVkX1+..."},"generatedAt":{"type":"string","format":"date-time","example":"2024-01-15T10:30:00Z"},"hasApiKey":{"type":"boolean","example":true}}},"UserRegistrationData":{"type":"object","required":["first_name","last_name","email","phone_no"],"properties":{"first_name":{"type":"string","example":"John","description":"User's first name"},"last_name":{"type":"string","example":"Doe","description":"User's last name"},"email":{"type":"string","format":"email","example":"john.doe@example.com","description":"User's email address (must be unique)"},"phone_no":{"type":"string","example":"+919876543210","description":"User's phone number with country code"},"userWithoutCompanyDetail":{"type":"boolean","default":false,"description":"Set to true if registering user without company details"},"referredToken":{"type":"string","description":"Encrypted referral token for sub-user registration"},"isOwnershipClaimed":{"type":"boolean","default":false,"description":"Set to true if claiming ownership of existing company"},"isMultiBranch":{"type":"boolean","default":false,"description":"Set to true if registering a branch of existing company"}}},"CompanyRegistrationData":{"type":"object","required":["company_name","gst_no","pan","segment","vertical"],"properties":{"company_name":{"type":"string","example":"ABC Electronics Pvt Ltd","description":"Legal company name"},"contact_person":{"type":"string","example":"John Doe","description":"Primary contact person name"},"contact_person_designation":{"type":"string","example":"Managing Director","description":"Designation of contact person"},"gst_no":{"type":"string","example":"27AABCU9603R1ZM","description":"GST number (must be unique)"},"pan":{"type":"string","example":"AABCU9603R","description":"PAN number (must be unique)"},"segment":{"type":"string","example":"Electronics","description":"Business segment (Electronics, Pharma, FMCG, etc.)"},"vertical":{"type":"string","example":"Retail","description":"Business vertical (Retail, Wholesale, Manufacturing, etc.)"},"turnover":{"type":"string","example":"10-50 Crores","description":"Annual turnover range"},"company_phone_no":{"type":"string","example":"+912212345678","description":"Company phone number"},"drug_license_no":{"type":"string","description":"Drug license number (for Pharma segment)"},"food_registeration_no":{"type":"string","description":"FSSAI registration number (for FMCG segment)"},"restaurant_license_no":{"type":"string","description":"Restaurant license number (for Food & Beverage)"},"address":{"type":"object","required":["street_address","city","state","country"],"properties":{"street_address":{"type":"string","example":"123, MG Road"},"city":{"type":"string","example":"Mumbai"},"state":{"type":"string","example":"Maharashtra"},"country":{"type":"string","example":"India"}}},"alias":{"type":"string","example":"abc-electronics","description":"Company alias for multi-branch (auto-generated if not provided)"}}},"OwnershipClaimData":{"type":"object","required":["company_name","gst_no","pan","email"],"properties":{"company_name":{"type":"string","example":"XYZ Pharma Ltd"},"gst_no":{"type":"string","example":"27AABCX1234R1ZM"},"pan":{"type":"string","example":"AABCX1234R"},"email":{"type":"string","format":"email","example":"owner@xyzpharma.com"}}},"LoginResponse":{"type":"object","properties":{"success":{"type":"boolean","example":true},"token":{"type":"string","example":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...","description":"JWT token for subsequent authenticated requests"},"user":{"type":"object","properties":{"_id":{"type":"string","example":"507f1f77bcf86cd799439011"},"email":{"type":"string","example":"john.doe@example.com"},"userName":{"type":"string","example":"John Doe"},"phone_no":{"type":"string","example":"+919876543210"},"companyName":{"type":"string","example":"ABC Electronics Pvt Ltd"},"companyId":{"type":"string","example":"507f1f77bcf86cd799439012"},"role":{"type":"string","example":"ADMIN","enum":["ADMIN","USER","MANAGER","VIEWER"]},"gst_no":{"type":"string","example":"27AABCU9603R1ZM"},"pan":{"type":"string","example":"AABCU9603R"},"isMultiBranch":{"type":"boolean","example":false}}}}},"RegistrationResponse":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"User registered successfully"},"data":{"type":"object","properties":{"user":{"type":"object","description":"Created user object"},"companyDetail":{"type":"object","description":"Created company details"},"isMultiBranch":{"type":"boolean","description":"Whether this is a multi-branch registration"},"masterCompanyDetail":{"type":"object","description":"Master company details (for multi-branch)"}}}}},"ApiKeyLoginResponse":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Login successful"},"token":{"type":"string","example":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."},"user":{"type":"object","properties":{"_id":{"type":"string"},"email":{"type":"string"},"userName":{"type":"string"},"phone_no":{"type":"string"}}},"company":{"type":"object","properties":{"name":{"type":"string"},"gst_no":{"type":"string"},"pan":{"type":"string"},"store_id":{"type":"string"},"isMultiBranch":{"type":"boolean"}}}}},"GSTVerificationResponse":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"GSTIN is Valid"}}},"CompanyProfile":{"type":"object","properties":{"_id":{"type":"string","example":"507f1f77bcf86cd799439012"},"company_name":{"type":"string","example":"ABC Electronics Pvt Ltd"},"contact_person":{"type":"string","example":"John Doe"},"contact_person_designation":{"type":"string","example":"Managing Director"},"gst_no":{"type":"string","example":"27AABCU9603R1ZM"},"pan":{"type":"string","example":"AABCU9603R"},"segment":{"type":"string","example":"Electronics"},"vertical":{"type":"string","example":"Retail"},"turnover":{"type":"string","example":"10-50 Crores"},"company_phone_no":{"type":"string","example":"+912212345678"},"address":{"type":"object","properties":{"street_address":{"type":"string","example":"123, MG Road"},"city":{"type":"string","example":"Mumbai"},"state":{"type":"string","example":"Maharashtra"},"country":{"type":"string","example":"India"}}},"gst_certificate":{"type":"object","properties":{"secure_url":{"type":"string","example":"https://storage.example.com/gst_cert.pdf"}}},"pan_certificate":{"type":"object","properties":{"secure_url":{"type":"string","example":"https://storage.example.com/pan_cert.pdf"}}},"company_profile_img":{"type":"object","properties":{"secure_url":{"type":"string","example":"https://storage.example.com/profile.jpg"}}},"api_key":{"type":"string","example":"U2FsdGVkX1+abc123...encrypted_api_key"},"store_id":{"type":"string","example":"a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6"},"isMultiBranch":{"type":"boolean","example":false},"parent_company_id":{"type":"string","example":"507f1f77bcf86cd799439013"},"alias":{"type":"string","example":"abc-electronics"}}},"CompanyUpdateData":{"type":"object","properties":{"company_name":{"type":"string","example":"ABC Electronics Pvt Ltd"},"contact_person":{"type":"string","example":"John Doe"},"contact_person_designation":{"type":"string","example":"Managing Director"},"company_phone_no":{"type":"string","example":"+912212345678"},"address":{"type":"object","properties":{"street_address":{"type":"string"},"city":{"type":"string"},"state":{"type":"string"},"country":{"type":"string"}}},"turnover":{"type":"string","example":"10-50 Crores"}}},"CompanySearchResult":{"type":"object","properties":{"company_name":{"type":"string","example":"ABC Electronics Pvt Ltd"},"gst_no":{"type":"string","example":"27AABCU9603R1ZM"},"pan":{"type":"string","example":"AABCU9603R"},"station":{"type":"string","example":"Mumbai"}}},"BranchInfo":{"type":"object","properties":{"company_name":{"type":"string","example":"ABC Electronics - Branch 1"},"gst_no":{"type":"string","example":"27AABCU9603R1ZM"},"pan":{"type":"string","example":"AABCU9603R"},"address":{"type":"object"},"parent_company_id":{"type":"string","example":"507f1f77bcf86cd799439012"},"userDetail":{"type":"object","properties":{"userName":{"type":"string","example":"Jane Smith"},"email":{"type":"string","example":"jane.smith@abcelectronics.com"},"phone_no":{"type":"string","example":"+919876543211"},"isActive":{"type":"boolean","example":true},"accountStatus":{"type":"string","example":"APPROVED","enum":["PENDING","APPROVED","REJECTED"]}}}}},"CompanyStatistics":{"type":"object","properties":{"totalCompanies":{"type":"integer","example":1500},"activeCompanies":{"type":"integer","example":1450},"multiBranchCompanies":{"type":"integer","example":250},"companiesWithGST":{"type":"integer","example":1400},"companiesWithPAN":{"type":"integer","example":1500}}},"CsvMappingItem":{"type":"object","properties":{"key":{"type":"string","description":"Logical field key (e.g., TransactionDetails.transactionID)"},"selected_value":{"type":"string","description":"Source column name or value mapping"},"csvIndex":{"type":"integer","description":"CSV column index (0-based)"}}},"CsvDefinationHTF":{"type":"object","properties":{"headerItem":{"type":"array","items":{"$ref":"#/components/schemas/CsvMappingItem"}},"lineItem":{"type":"array","items":{"$ref":"#/components/schemas/CsvMappingItem"}},"footerItem":{"type":"array","items":{"$ref":"#/components/schemas/CsvMappingItem"}}}},"CsvDefinition":{"type":"object","properties":{"_id":{"type":"string"},"name":{"type":"string"},"description":{"type":"string"},"is_htf_format":{"type":"boolean","description":"True for structured HTF mapping; false for flat/header mapping"},"csvDefination":{"$ref":"#/components/schemas/CsvDefinationHTF"},"csvHeaderNames":{"type":"array","items":{"type":"string"},"description":"Flat/header mode header names to match against CSV"},"isDefault":{"type":"boolean"},"company_id":{"type":"string"},"createdAt":{"type":"string","format":"date-time"},"updatedAt":{"type":"string","format":"date-time"}}},"CsvDefinitionsListResponse":{"type":"object","properties":{"success":{"type":"boolean"},"message":{"type":"string"},"data":{"type":"object","properties":{"items":{"type":"array","items":{"$ref":"#/components/schemas/CsvDefinition"}},"pagination":{"type":"object","properties":{"page":{"type":"integer"},"limit":{"type":"integer"},"total":{"type":"integer"},"pages":{"type":"integer"}}}}}}},"CsvDefinitionResponse":{"type":"object","properties":{"success":{"type":"boolean"},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/CsvDefinition"}}},"CsvDetectResponse":{"type":"object","properties":{"success":{"type":"boolean"},"message":{"type":"string"},"data":{"type":"object","properties":{"match":{"type":"object","nullable":true,"properties":{"_id":{"type":"string"},"name":{"type":"string"},"score":{"type":"number"},"isDefault":{"type":"boolean"}}},"headerNames":{"type":"array","items":{"type":"string"}}}}}},"TransactionStats":{"type":"object","properties":{"transactionCount":{"type":"integer","description":"Total number of transactions","example":150},"purchaseInvoiceLength":{"type":"integer","description":"Number of purchase invoices received","example":25},"salesOrderLength":{"type":"integer","description":"Number of sales orders received","example":30},"purchaseChallanLength":{"type":"integer","description":"Number of purchase challans received","example":15},"salesReturnLength":{"type":"integer","description":"Number of sales returns received","example":5},"salesInvoiceLength":{"type":"integer","description":"Number of sales invoices sent","example":40},"purchaseOrderLength":{"type":"integer","description":"Number of purchase orders sent","example":20},"salesChallanLength":{"type":"integer","description":"Number of sales challans sent","example":10},"purchaseReturnLength":{"type":"integer","description":"Number of purchase returns sent","example":5},"purchaseInvoiceDownloaded":{"type":"integer","description":"Number of downloaded purchase invoices","example":20},"purchaseInvoiceNotDownloaded":{"type":"integer","description":"Number of not downloaded purchase invoices","example":5},"salesOrderDownloaded":{"type":"integer","description":"Number of downloaded sales orders","example":25},"salesOrderNotDownloaded":{"type":"integer","description":"Number of not downloaded sales orders","example":5},"purchaseChallanDownloaded":{"type":"integer","description":"Number of downloaded purchase challans","example":12},"purchaseChallanNotDownloaded":{"type":"integer","description":"Number of not downloaded purchase challans","example":3},"salesReturnDownloaded":{"type":"integer","description":"Number of downloaded sales returns","example":4},"salesReturnNotDownloaded":{"type":"integer","description":"Number of not downloaded sales returns","example":1},"salesInvoiceDownloaded":{"type":"integer","description":"Number of downloaded sales invoices","example":35},"salesInvoiceNotDownloaded":{"type":"integer","description":"Number of not downloaded sales invoices","example":5},"purchaseOrderDownloaded":{"type":"integer","description":"Number of downloaded purchase orders","example":18},"purchaseOrderNotDownloaded":{"type":"integer","description":"Number of not downloaded purchase orders","example":2},"salesChallanDownloaded":{"type":"integer","description":"Number of downloaded sales challans","example":8},"salesChallanNotDownloaded":{"type":"integer","description":"Number of not downloaded sales challans","example":2},"purchaseReturnDownloaded":{"type":"integer","description":"Number of downloaded purchase returns","example":4},"purchaseReturnNotDownloaded":{"type":"integer","description":"Number of not downloaded purchase returns","example":1}}},"GraphDataPoint":{"type":"object","properties":{"total_transactions":{"type":"integer","description":"Total transactions (sent + received) for the month","example":25},"total_sent":{"type":"integer","description":"Total sent transactions for the month","example":15},"total_received":{"type":"integer","description":"Total received transactions for the month","example":10},"sales_invoice":{"type":"integer","description":"Number of sales invoices sent","example":8},"purchase_invoice":{"type":"integer","description":"Number of purchase invoices received","example":6},"sales_order":{"type":"integer","description":"Number of sales orders received","example":4},"purchase_order":{"type":"integer","description":"Number of purchase orders sent","example":7}}},"GraphDataMonth":{"type":"object","properties":{"month":{"type":"string","description":"Month name","example":"April"},"data":{"$ref":"#/components/schemas/GraphDataPoint"}}},"TransactionGraphData":{"type":"object","properties":{"graphData":{"type":"array","items":{"$ref":"#/components/schemas/GraphDataMonth"},"description":"Monthly transaction data for the fiscal year"},"year":{"type":"integer","description":"Fiscal year start","example":2024},"queryMethod":{"type":"string","description":"Query method used","example":"optimized_aggregation"},"dataPoints":{"type":"object","properties":{"sender":{"type":"integer","description":"Number of sender data points","example":24},"receiver":{"type":"integer","description":"Number of receiver data points","example":18},"total":{"type":"integer","description":"Total data points","example":42}}}}},"DashboardStatsResponse":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Transaction statistics retrieved successfully"},"data":{"$ref":"#/components/schemas/TransactionStats"}}},"DashboardGraphResponse":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Transaction graph data retrieved successfully"},"data":{"$ref":"#/components/schemas/TransactionGraphData"}}},"StandardError":{"type":"object","properties":{"success":{"type":"boolean","example":false},"statusCode":{"type":"integer","example":400},"message":{"type":"string","example":"Invalid year parameter"}}},"MailSender":{"type":"object","properties":{"name":{"type":"string"},"email":{"type":"string"},"company_name":{"type":"string"}}},"MailAttachment":{"type":"object","properties":{"url":{"type":"string"},"file_name":{"type":"string"},"file_size":{"type":"string"},"file_type":{"type":"string"},"isImported":{"type":"boolean"}}},"Mail":{"type":"object","properties":{"_id":{"type":"string"},"receiver":{"type":"string"},"sender":{"$ref":"#/components/schemas/MailSender"},"subject":{"type":"string"},"message":{"type":"string"},"mail_receivedAt":{"type":"string","format":"date-time"},"mail_thread_id":{"type":"string"},"mark_as_read":{"type":"boolean"},"attachments":{"type":"array","items":{"$ref":"#/components/schemas/MailAttachment"}},"createdAt":{"type":"string","format":"date-time"},"updatedAt":{"type":"string","format":"date-time"}}},"MailListResponse":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Mails fetched"},"data":{"type":"array","items":{"$ref":"#/components/schemas/Mail"}}}},"MailMutationResponse":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string"},"data":{"type":"object","properties":{"id":{"type":"string"},"mark_as_read":{"type":"boolean"},"deleted":{"type":"boolean"}}}}},"MastersType":{"type":"string","enum":["country","state","pincode","currency","unit"]},"MasterCountry":{"type":"object","properties":{"name":{"type":"string"},"code":{"type":"string"}}},"MasterState":{"type":"object","properties":{"name":{"type":"string"},"code":{"type":"integer"}}},"MasterPincode":{"type":"object","properties":{"code":{"type":"integer"},"name":{"type":"string"},"rangeOfPincode":{"type":"string"}}},"MasterCurrency":{"type":"object","properties":{"country":{"type":"string"},"currency_code":{"type":"string"}}},"MasterUnit":{"type":"object","properties":{"unitCode":{"type":"string"},"unit":{"type":"string"}}},"MastersGetResponse":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Masters fetched successfully"},"data":{"type":"object","additionalProperties":false,"properties":{"country":{"type":"array","items":{"$ref":"#/components/schemas/MasterCountry"}},"state":{"type":"array","items":{"$ref":"#/components/schemas/MasterState"}},"pincode":{"type":"array","items":{"$ref":"#/components/schemas/MasterPincode"}},"currency":{"type":"array","items":{"$ref":"#/components/schemas/MasterCurrency"}},"unit":{"type":"array","items":{"$ref":"#/components/schemas/MasterUnit"}}}}}},"MastersMutationResponse":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Masters saved successfully"},"data":{"type":"object","additionalProperties":true}}},"ReportsControllerError":{"type":"object","description":"Reports controller try/catch. Uses ApiError.status as HTTP status.","required":["success","statusCode","message"],"properties":{"success":{"type":"boolean","example":false},"statusCode":{"type":"integer"},"message":{"type":"string"}}},"ExpressApiErrorBody":{"type":"object","description":"Global error middleware response for next(ApiError). Used for JWT auth failures and ensureCompanyUser 403.","properties":{"success":{"type":"boolean","example":false},"statusCode":{"type":"integer"},"message":{"type":"string"},"code":{"type":"string","description":"ErrorCodes value from api-error.js when present."},"details":{"type":"object"}}},"ReportsHttp401":{"type":"object","description":"Combined documentation for 401 responses. Actual JSON varies by path:\neitherAuthOrKeys (no credentials): success and message only.\nvalidateApiKey: success and message (missing or invalid API key).\nvalidateAnyKey: success and error (app key uses field name error, not message).\nJWT valid path but auth fails via next(ApiError): same shape as ExpressApiErrorBody.\n","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string"},"error":{"type":"string"},"statusCode":{"type":"integer"},"code":{"type":"string"}}},"ReportsHttp403":{"type":"object","description":"Includes API key suspended account (accountSuspended true), attachUserFromApiCompany company owner missing,\nJWT deactivated account, downloadReport access denied (controller), or plain message for other forbids.\nRoutes using next(ApiError) may return ExpressApiErrorBody instead.\n","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string"},"accountSuspended":{"type":"boolean"},"statusCode":{"type":"integer"},"code":{"type":"string"}}},"ReportsHttp404":{"type":"object","description":"Company not found for Bearer user (eitherAuthOrKeys), or report not found (service).","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string"},"statusCode":{"type":"integer"},"code":{"type":"string"}}},"ReportsHttp429":{"type":"object","description":"API key hourly rate limit (api-key.middleware).","required":["success","message"],"properties":{"success":{"type":"boolean","example":false},"message":{"type":"string"},"resetTime":{"type":"string","format":"date-time"}}},"ReportsHttp500":{"type":"object","description":"Middleware internal errors (often message plus error detail string), controller catch-all,\nor service failures. Prefer statusCode when present from controller.\n","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string"},"statusCode":{"type":"integer"},"error":{"type":"string"}}},"AsyncHandler500Body":{"type":"object","description":"Non-HTTP errors thrown past controller try/catch but caught by asyncHandler (fixed message, HTTP 500).","required":["success","message"],"properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Internal server error"}}},"SuccessReport":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/Report"}}},"SuccessReportList":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string"},"data":{"type":"array","items":{"$ref":"#/components/schemas/Report"}}}},"SuccessDeleteReport":{"type":"object","description":"No data field on delete success.","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string"}}},"ReportStatistics":{"type":"object","description":"Aggregated counts for reports where the user is sender or receiver.","properties":{"totalReports":{"type":"integer","example":42},"sentReports":{"type":"integer"},"receivedReports":{"type":"integer"},"pdfReports":{"type":"integer"},"csvReports":{"type":"integer"}}},"SuccessStatistics":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string"},"data":{"$ref":"#/components/schemas/ReportStatistics"}}},"MrUserSummary":{"type":"object","properties":{"_id":{"type":"string"},"userName":{"type":"string"},"email":{"type":"string","format":"email"}}},"SuccessMrUsers":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string"},"data":{"type":"array","items":{"$ref":"#/components/schemas/MrUserSummary"}}}},"CompanyAccessedMrUsersResponse":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string"},"data":{"description":"MR relationship rows for the company (shape from service).","type":"array","items":{"type":"object"}}}},"ReportDetails":{"type":"object","properties":{"reportType":{"type":"string"},"report_name":{"type":"string"},"report_date":{"type":"object","properties":{"from":{"type":"string"},"to":{"type":"string"}}},"report_link":{"type":"string"},"file_type":{"type":"string","enum":["pdf","csv"]}}},"Party":{"type":"object","properties":{"companyName":{"type":"string"},"contactPerson":{"type":"string"},"pan":{"type":"string"},"gstin":{"type":"string"},"phone":{"type":"number"},"email":{"type":"string"},"address":{"type":"object","properties":{"fullAddress":{"type":"string"},"pincode":{"type":"number"},"city":{"type":"string"},"state":{"type":"string"},"country":{"type":"string"}}}}},"Report":{"type":"object","properties":{"_id":{"type":"string"},"reportDetails":{"$ref":"#/components/schemas/ReportDetails"},"sender":{"$ref":"#/components/schemas/Party"},"receiver":{"$ref":"#/components/schemas/Party"},"companyId":{"type":"string"},"createdAt":{"type":"string","format":"date-time"},"updatedAt":{"type":"string","format":"date-time"}}},"PaginatedReportsResponse":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string"},"data":{"type":"array","items":{"$ref":"#/components/schemas/Report"}},"pagination":{"type":"object","properties":{"page":{"type":"integer"},"limit":{"type":"integer"},"total":{"type":"integer"},"pages":{"type":"integer"}}}}},"TransactionDetails":{"type":"object","required":["transactionDate","transactionType","transactionID"],"properties":{"transactionDate":{"type":"string","description":"Date of transaction in YYYY-MM-DD or YYYY/MM/DD format","example":"2024/02/23"},"transactionType":{"type":"string","enum":["Sales Invoice","Purchase Invoice","Sales Order","Purchase Order","Sales Challan","Purchase Challan","Sales Return","Purchase Return"],"description":"Type of transaction. For receivers, the type is automatically mapped (e.g., Purchase Invoice → Sales Invoice)","example":"Sales Invoice"},"supplyType":{"type":"string","description":"Type of supply (e.g., B2B, B2C)","example":"B2B"},"transactionID":{"type":"string","description":"Unique identifier for the transaction within your system","example":"INV-001"},"transactionNoPrefix":{"type":"string"},"isReverseChargeApplicable":{"type":"boolean"},"isIgstApplicableOnIntraState":{"type":"boolean"},"ecommerceProviderGstin":{"type":"string"},"transactionCurrencyCode":{"type":"string"},"taxCurrencyCode":{"type":"string"},"RefNo":{"type":"string"},"RefDate":{"type":"string"},"RatesInclTax":{"type":"boolean"}}},"PartyDetails":{"type":"object","properties":{"name":{"type":"string","description":"Party display name"},"email":{"type":"string","format":"email","example":"company@example.com"},"tradeName":{"type":"string","example":"ABC Trading Co"},"legalName":{"type":"string","example":"ABC Trading Company Pvt Ltd"},"gstin":{"type":"string","example":"27AAACC1234B1ZA"},"pan":{"type":"string","example":"AAACC1234B"},"phone":{"type":"string","example":"9999999999"},"address":{"type":"object","properties":{"line1":{"type":"string"},"line2":{"type":"string"},"location":{"type":"string"},"pincode":{"type":"string"},"state":{"type":"string"},"stateCode":{"type":"string"}}},"License1":{"type":"string"},"License2":{"type":"string"},"License3":{"type":"string"},"License4":{"type":"string"},"License5":{"type":"string"}}},"ProductDetails":{"type":"object","properties":{"CompanyProductCode":{"type":"string"},"CompanyCode":{"type":"string"},"CompanyName":{"type":"string"},"Alias":{"type":"string"},"Category":{"type":"string"},"Marketing":{"type":"string"},"Brand":{"type":"string"},"Manufacturer":{"type":"string"},"CountryofManufacturing":{"type":"string"},"IMEIcode":{"type":"string"},"ModelNo":{"type":"string"},"PRDserialNo":{"type":"string"},"Type":{"type":"string"},"Size":{"type":"string"},"Color":{"type":"string"},"Strength":{"type":"string"},"Flavour":{"type":"string"},"Salts":{"type":"string"},"Scheduletype":{"type":"string"},"Length":{"type":"number"},"Width":{"type":"number"},"Height":{"type":"number"},"Weight":{"type":"number"},"ManufactureDate":{"type":"string"},"BestBefore":{"type":"number"},"DisplayName":{"type":"string"},"GroupName":{"type":"string"},"UnitofMeasurement2":{"type":"string"},"UnitofMeasurement3":{"type":"string"},"UnitofMeasurement2Size":{"type":"string"},"UnitofMeasurement3Size":{"type":"string"},"Remarks":{"type":"string"}}},"LineItem":{"type":"object","properties":{"serialNumber":{"type":"number"},"productName":{"type":"string"},"description":{"type":"string"},"isService":{"type":"boolean"},"hsnCode":{"type":"string"},"skuCode":{"type":"string"},"Barcode":{"type":"string"},"BatchNumber":{"type":"string"},"MRP":{"type":"number"},"IGSTPrec":{"type":"number"},"CGSTPrec":{"type":"number"},"SGSTPrec":{"type":"number"},"Remarks":{"type":"string"},"ExpiryDate":{"type":"string"},"ProductDetails":{"$ref":"#/components/schemas/ProductDetails"},"pricePerUnit":{"type":"number"},"discountPerUnit":{"type":"number"},"taxableAmount":{"type":"number"},"cessRate":{"type":"number"},"stateCessRate":{"type":"number"},"cessNonAdvolAmount":{"type":"number"},"stateCessNonAdvolAmount":{"type":"number"},"Quantity":{"type":"number"},"FreeQuantity":{"type":"number"},"unitOfMeasurement":{"type":"string"},"otherCharges":{"type":"number"},"igstAmount":{"type":"number"},"cgstAmount":{"type":"number"},"sgstAmount":{"type":"number"},"cessAmount":{"type":"number"},"stateCessAmount":{"type":"number"},"grossAmount":{"type":"number"},"totalItemValue":{"type":"number"},"PTRDiscount":{"type":"number"},"PTSDiscount":{"type":"number"},"SchemeDiscType":{"type":"string","enum":["R","P","T","A"]},"LotDisc":{"type":"number"},"returnType":{"type":"string"},"Deduction":{"type":"number"},"taxCategory":{"type":"string"},"discount":{"type":"number"},"PricetoRetailer":{"type":"number"},"PricetoSupplier":{"type":"number"},"Scheme":{"type":"string"},"TaxCalcMethod":{"type":"string"},"RefDocDate":{"type":"string"},"RefDocNo":{"type":"string"}}},"ValueDetails":{"type":"object","properties":{"totalTaxableAmount":{"type":"number"},"totalCgstAmount":{"type":"number"},"totalIgstAmount":{"type":"number"},"totalSgstAmount":{"type":"number"},"totalCessAmount":{"type":"number"},"totalStateCessAmount":{"type":"number"},"totalDiscountAmount":{"type":"number"},"totalAdditionalChargeAmount":{"type":"number"},"totalRoundOffAmount":{"type":"number"},"totalAmount":{"type":"number"},"totalTaxAmount":{"type":"number"},"totalAmountInForeignCurrency":{"type":"number"},"totalCashDiscountAmount":{"type":"number"},"totalFreightAmount":{"type":"number"},"FreightType":{"type":"string"}}},"Transaction":{"type":"object","required":["TransactionDetails","upload_by"],"properties":{"_id":{"type":"string","description":"MongoDB ID of the transaction"},"TransactionDetails":{"$ref":"#/components/schemas/TransactionDetails"},"senderDetails":{"$ref":"#/components/schemas/PartyDetails"},"receiverDetails":{"$ref":"#/components/schemas/PartyDetails"},"dispatchDetails":{"$ref":"#/components/schemas/PartyDetails"},"shippingDetails":{"$ref":"#/components/schemas/PartyDetails"},"lineItems":{"type":"array","items":{"$ref":"#/components/schemas/LineItem"}},"valueDetails":{"$ref":"#/components/schemas/ValueDetails"},"reUpload":{"type":"boolean","description":"Transaction-level reUpload flag. When true, allows re-uploading of this specific transaction even if it has been downloaded.","default":false,"example":true},"downloadable":{"type":"boolean"},"otherCharges":{"type":"array","items":{"type":"object","properties":{"Description":{"type":"string"},"Amount":{"type":"number"},"IGSTRate":{"type":"number"},"CGSTRate":{"type":"number"},"SGSTRate":{"type":"number"},"CessRate":{"type":"number"},"IGSTAmount":{"type":"number"},"CGSTAmount":{"type":"number"},"SGSTAmount":{"type":"number"},"CessAmount":{"type":"number"},"TaxableAmount":{"type":"number"},"NetAmount":{"type":"number"},"AddLess":{"type":"string"},"HSNCode":{"type":"string"}}}},"log":{"type":"array","items":{"type":"object","properties":{"download_log":{"type":"array","items":{"type":"object","properties":{"download_by":{"type":"string"},"download_from":{"type":"string"},"download_at":{"type":"string","format":"date-time"},"isDownloaded":{"type":"boolean"}}}},"upload_at":{"type":"string","format":"date-time"},"cancel_log":{"type":"object","properties":{"cancel_by":{"type":"string"},"cancel_from":{"type":"string"},"cancel_at":{"type":"string","format":"date-time"},"isCanceled":{"type":"boolean"}}},"expiry_log":{"type":"object","properties":{"expiry_by":{"type":"string"},"expiry_at":{"type":"string","format":"date-time"},"isExpired":{"type":"boolean"},"expiry_reason":{"type":"string","enum":["","EXPIRED","USER_REQUEST"]}}}}}},"upload_by":{"type":"string"},"upload_from":{"type":"string","default":"system"}}},"Error":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string"},"code":{"type":"string","description":"Error code for programmatic handling"},"data":{"type":"object","description":"Additional error context"}}},"PaginationResponse":{"type":"object","properties":{"page":{"type":"integer","description":"Current page number"},"limit":{"type":"integer","description":"Items per page"},"total":{"type":"integer","description":"Total number of items"},"pages":{"type":"integer","description":"Total number of pages"}}},"UserProfile":{"type":"object","properties":{"_id":{"type":"string","example":"507f1f77bcf86cd799439011"},"userName":{"type":"string","example":"John Doe"},"email":{"type":"string","example":"user@example.com"},"phone_no":{"type":"string","example":"+919876543210"},"role":{"type":"string","enum":["ADMIN","USER","GUEST_USER"],"example":"ADMIN"},"isActive":{"type":"boolean","example":true},"accountStatus":{"type":"string","enum":["PENDING","APPROVED","REJECTED","CLAIMED"],"example":"APPROVED"},"createdAt":{"type":"string","format":"date-time"},"companyDetail":{"type":"object","properties":{"_id":{"type":"string"},"company_name":{"type":"string"},"gst_no":{"type":"string"},"pan":{"type":"string"}}}}},"SubUser":{"type":"object","properties":{"_id":{"type":"string"},"userName":{"type":"string"},"email":{"type":"string"},"phone_no":{"type":"string"},"isActive":{"type":"boolean"},"assigned_company":{"type":"object","properties":{"company_id":{"type":"object","properties":{"_id":{"type":"string"},"company_profile_img":{"type":"string"}}},"role":{"type":"string"}}}}},"UserStatistics":{"type":"object","properties":{"totalUsers":{"type":"integer","example":1500},"activeUsers":{"type":"integer","example":1400},"adminUsers":{"type":"integer","example":1200},"guestUsers":{"type":"integer","example":300},"approvedUsers":{"type":"integer","example":1300},"pendingUsers":{"type":"integer","example":200}}}}},"paths":{"/admin/registered-users":{"get":{"summary":"Get registered users with filters","description":"Retrieve list of registered users with optional filters and pagination.\nReturns both master company users and branch users.\n\n**Authentication Required**: Yes (Super Admin)\n\n**Filter Options**:\n- gstin: Filter by GST number (exact match)\n- pan: Filter by PAN number (exact match)\n- company_name: Filter by company name (exact match, case-insensitive)\n- account_status: Filter by account status\n\n**Pagination**: 20 users per page\n\n**Use Cases**:\n- View all registered users\n- Search users by company details\n- Filter by account status\n- Review pending approvals\n- Monitor user activity\n\n**Consumption Profile**: Admin (admin.swilunify.com)\n","tags":["Admin Management"],"security":[{"BearerAuth":[]},{"AppKeyAuth":[]}],"parameters":[{"in":"query","name":"offset","schema":{"type":"integer","default":0,"minimum":0},"description":"Page offset for pagination (0-based)"},{"in":"query","name":"gstin","schema":{"type":"string","example":"27AABCU9603R1ZM"},"description":"Filter by GST number (exact match)"},{"in":"query","name":"pan","schema":{"type":"string","example":"AABCU9603R"},"description":"Filter by PAN number (exact match)"},{"in":"query","name":"company_name","schema":{"type":"string","example":"ABC Electronics Pvt Ltd"},"description":"Filter by company name (exact match, case-insensitive)"},{"in":"query","name":"company_name_contains","schema":{"type":"string","example":"ABC"},"description":"Partial case-insensitive match on company name (preferred for search UI)"},{"in":"query","name":"search_contains","schema":{"type":"string","example":"pharma"},"description":"Partial case-insensitive match on **company legal name**, **user email**, or **user phone** (any match).\nIf set, takes precedence over `company_name_contains` for the same text-style search.\n"},{"in":"query","name":"account_status","schema":{"type":"string","enum":["ALL","APPROVED","CLAIMED","PENDING","REJECTED"],"example":"PENDING"},"description":"Filter by account status for **both** master-company admins and branch admins.\n`ALL` returns every status (no filter).\n"}],"responses":{"200":{"description":"Registered users retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Registered users retrieved successfully"},"data":{"type":"object","properties":{"users":{"type":"array","items":{"$ref":"#/components/schemas/RegisteredUser"}},"pagination":{"type":"object","properties":{"page":{"type":"integer","example":1},"limit":{"type":"integer","example":20},"total":{"type":"integer","example":15}}}}}}}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"403":{"description":"Forbidden - Super admin access required","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/admin/registered-users/{id}":{"get":{"summary":"Get specific registered user details","description":"Retrieve detailed information about a specific registered user\nincluding company details and account status.\n\n**Authentication Required**: Yes (Super Admin)\n\n**Returns**: Complete user profile with company information\n\n**Use Cases**:\n- View user details for approval\n- Review company information\n- Verify user credentials\n- Check account status\n\n**Consumption Profile**: Admin (admin.swilunify.com)\n","tags":["Admin Management"],"security":[{"BearerAuth":[]},{"AppKeyAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","example":"507f1f77bcf86cd799439011"},"description":"User ID (MongoDB ObjectId)"}],"responses":{"200":{"description":"User details retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"User details retrieved successfully"},"data":{"type":"array","items":{"type":"object","properties":{"_id":{"type":"string"},"email":{"type":"string"},"userName":{"type":"string"},"phone_no":{"type":"string"},"accountStatus":{"type":"string"},"role":{"type":"string"},"isActive":{"type":"boolean"},"companyDetail":{"type":"object"},"createdAt":{"type":"string","format":"date-time"}}}}}}}}},"400":{"description":"Invalid user ID","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"403":{"description":"Forbidden - Super admin access required","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"404":{"description":"User not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/admin/administrative-rights":{"post":{"summary":"Handle administrative rights (approve/reject accounts, ownership, MR users)","description":"Perform various administrative actions on user accounts.\nThis is a multi-purpose endpoint that handles different types of admin actions.\n\n**Authentication Required**: Yes (Super Admin)\n\n**Action Types**:\n1. **Account Approval/Rejection** (signupAccountStatus)\n   - true: Approve account (set status to APPROVED, activate user)\n   - false: Reject account (set status to REJECTED, deactivate user)\n\n2. **Ownership Provision** (isOnwershipProvided)\n   - true: Grant ownership (activate account, set CLAIMED status)\n   - false: Revoke ownership (block account, send notification email)\n\n3. **MR User Management** (isMrUserBlock)\n   - true: Unblock MR user (activate account)\n   - false: Block MR user (deactivate account)\n\n**Business Rules**:\n- Only one action type per request\n- Admin username logged for audit trail\n- Email notifications sent for ownership revocation\n- Linked users affected in ownership actions\n\n**Use Cases**:\n- Approve new user registrations\n- Reject fraudulent accounts\n- Resolve ownership disputes\n- Manage MR user access\n- Handle multi-branch approvals\n\n**Consumption Profile**: Admin (admin.swilunify.com)\n","tags":["Admin Management"],"security":[{"BearerAuth":[]},{"AppKeyAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"signupAccountStatus":{"type":"boolean","description":"Approve/reject account status.\ntrue = approve, false = reject\n","example":true},"isOnwershipProvided":{"type":"boolean","description":"Provide/revoke ownership.\ntrue = grant ownership, false = revoke ownership\n","example":true},"isMrUserBlock":{"type":"boolean","description":"Block/unblock MR user.\ntrue = unblock, false = block\n","example":false},"userId":{"type":"array","items":{"type":"string"},"description":"User ID(s) to perform action on","example":["507f1f77bcf86cd799439011"]},"isMultiBranchUser":{"type":"boolean","description":"Whether it's a multi-branch user (for ownership actions)","example":false}}},"examples":{"approveAccount":{"summary":"Approve user account","value":{"signupAccountStatus":true,"userId":["507f1f77bcf86cd799439011"]}},"rejectAccount":{"summary":"Reject user account","value":{"signupAccountStatus":false,"userId":["507f1f77bcf86cd799439011"]}},"grantOwnership":{"summary":"Grant company ownership","value":{"isOnwershipProvided":true,"userId":["507f1f77bcf86cd799439011"],"isMultiBranchUser":false}},"blockMRUser":{"summary":"Block MR user","value":{"isMrUserBlock":false,"userId":["507f1f77bcf86cd799439011"]}}}}}},"responses":{"200":{"description":"Administrative action completed successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Administrative action completed successfully"},"data":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Company account approved successfully"}}}}},"examples":{"accountApproved":{"summary":"Account approved","value":{"success":true,"message":"Administrative action completed successfully","data":{"success":true,"message":"Company account approved successfully"}}},"ownershipGranted":{"summary":"Ownership granted","value":{"success":true,"message":"Administrative action completed successfully","data":{"success":true,"message":"Ownership provided to company account successfully"}}},"mrUserBlocked":{"summary":"MR user blocked","value":{"success":true,"message":"Administrative action completed successfully","data":{"success":true,"message":"MR user blocked successfully"}}}}}}},"400":{"description":"Invalid input data or no valid action provided","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"example":{"success":false,"statusCode":400,"message":"No valid action provided"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"403":{"description":"Forbidden - Super admin access required","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/admin/ownership-forms":{"get":{"summary":"Get ownership forms/claims","description":"Retrieve list of all company ownership claims that need admin review.\nReturns users who have claimed ownership of existing companies.\n\n**Authentication Required**: Yes (Super Admin)\n\n**Returns**: List of users with ownership claims and their details\n\n**Use Cases**:\n- Review pending ownership claims\n- Verify ownership documentation\n- Resolve ownership disputes\n- Monitor ownership status\n\n**Consumption Profile**: Admin (admin.swilunify.com)\n","tags":["Admin Management"],"security":[{"BearerAuth":[]},{"AppKeyAuth":[]}],"responses":{"200":{"description":"Ownership forms retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Ownership forms retrieved successfully"},"data":{"type":"array","items":{"type":"object","properties":{"_id":{"type":"string"},"email":{"type":"string"},"userName":{"type":"string"},"phone_no":{"type":"string"},"accountStatus":{"type":"string"},"ownershipClaimed":{"type":"boolean"},"ownershipStatus":{"type":"string","enum":["BLOCKED","CLAIMED"]},"role":{"type":"string"},"isActive":{"type":"boolean"},"companyName":{"type":"string"},"gstin":{"type":"string"},"pan":{"type":"string"},"isMultiBranch":{"type":"boolean"},"actionBy":{"type":"object"},"createdAt":{"type":"string","format":"date-time"}}}}}}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"403":{"description":"Forbidden - Super admin access required","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/admin/ownership-forms/{id}":{"get":{"summary":"Get ownership user details","description":"Retrieve detailed information about a specific ownership claim\nincluding user details, company information, and ownership documents.\n\n**Authentication Required**: Yes (Super Admin)\n\n**Returns**: Complete ownership claim details with documents\n\n**Use Cases**:\n- Review ownership claim details\n- Verify ownership documents\n- Compare claimed vs existing company data\n- Make ownership decision\n\n**Consumption Profile**: Admin (admin.swilunify.com)\n","tags":["Admin Management"],"security":[{"BearerAuth":[]},{"AppKeyAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","example":"507f1f77bcf86cd799439011"},"description":"Ownership user ID (MongoDB ObjectId)"}],"responses":{"200":{"description":"Ownership user details retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Ownership user details retrieved successfully"},"data":{"type":"array","items":{"type":"object","properties":{"_id":{"type":"string"},"userName":{"type":"string"},"email":{"type":"string"},"phone_no":{"type":"string"},"isActive":{"type":"boolean"},"accountStatus":{"type":"string"},"ownershipClaimed":{"type":"boolean"},"companyDetail":{"type":"object","description":"Existing company details"},"ownershipDetail":{"type":"object","description":"Claimed ownership details with documents"}}}}}}}}},"400":{"description":"Invalid user ID","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"403":{"description":"Forbidden - Super admin access required","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"404":{"description":"Ownership user not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/admin/super-admins":{"get":{"summary":"Get super admin users","description":"Retrieve list of all super admin users in the system.\n\n**Authentication Required**: Yes (Super Admin)\n\n**Returns**: List of super admin users with their details\n\n**Use Cases**:\n- View all super admins\n- Manage admin access\n- Audit admin accounts\n\n**Consumption Profile**: Admin (admin.swilunify.com)\n","tags":["Admin Management"],"security":[{"BearerAuth":[]},{"AppKeyAuth":[]}],"responses":{"200":{"description":"Super admin users retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Super admin users retrieved successfully"},"data":{"type":"array","items":{"type":"object","properties":{"_id":{"type":"string"},"userName":{"type":"string"},"email":{"type":"string"},"phone_no":{"type":"string"},"role":{"type":"string","example":"USER"},"createdAt":{"type":"string","format":"date-time"}}}}}}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"403":{"description":"Forbidden - Super admin access required","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}},"post":{"summary":"Create super admin user","description":"Create a new super admin user account.\n\n**Authentication Required**: Yes (Super Admin)\n\n**Business Rules**:\n- Email must be unique\n- userName and email are required\n- Role automatically set to USER (super admin)\n\n**Use Cases**:\n- Add new admin to team\n- Grant admin access\n- Create system administrators\n\n**Consumption Profile**: Admin (admin.swilunify.com)\n","tags":["Admin Management"],"security":[{"BearerAuth":[]},{"AppKeyAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["userName","email"],"properties":{"userName":{"type":"string","example":"Admin User","description":"Super admin username"},"phone_no":{"type":"string","example":"+919876543210","description":"Phone number (optional)"},"email":{"type":"string","format":"email","example":"admin@swilunify.com","description":"Email address (must be unique)"}}}}}},"responses":{"200":{"description":"Super admin user created successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Super admin user created successfully"},"data":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Super user created successfully"},"user":{"type":"object"}}}}}}}},"400":{"description":"Invalid input data or missing required fields","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"example":{"success":false,"statusCode":400,"message":"Please provide all required details"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"403":{"description":"Forbidden - Super admin access required","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"409":{"description":"User already exists","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"example":{"success":false,"statusCode":409,"message":"User already exists"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/admin/super-admins/{id}":{"delete":{"summary":"Delete super admin user","description":"Delete a super admin user account from the system.\n\n**Authentication Required**: Yes (Super Admin)\n\n**Warning**: This action is permanent and cannot be undone.\n\n**Use Cases**:\n- Remove admin access\n- Delete inactive admin accounts\n- Revoke admin privileges\n\n**Consumption Profile**: Admin (admin.swilunify.com)\n","tags":["Admin Management"],"security":[{"BearerAuth":[]},{"AppKeyAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","example":"507f1f77bcf86cd799439011"},"description":"Super admin user ID (MongoDB ObjectId)"}],"responses":{"200":{"description":"Super admin user deleted successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Super admin user deleted successfully"},"data":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"User deleted successfully"}}}}}}}},"400":{"description":"Invalid user ID","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"403":{"description":"Forbidden - Super admin access required","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"404":{"description":"User not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"example":{"success":false,"statusCode":404,"message":"User not found"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/admin/statistics":{"get":{"summary":"Get admin statistics","description":"Retrieve comprehensive platform statistics and analytics.\nProvides insights into users, companies, and ownership claims.\n\n**Authentication Required**: Yes (Super Admin)\n\n**Statistics Included**:\n- **Users**: Total, active, admin, guest users\n- **Companies**: Total and active companies\n- **Ownership**: Total and pending ownership claims\n\n**Use Cases**:\n- Admin dashboard analytics\n- Platform health monitoring\n- Business intelligence reports\n- Growth metrics tracking\n- Compliance monitoring\n\n**Consumption Profile**: Admin (admin.swilunify.com)\n","tags":["Admin Management"],"security":[{"BearerAuth":[]},{"AppKeyAuth":[]}],"responses":{"200":{"description":"Admin statistics retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Admin statistics retrieved successfully"},"data":{"$ref":"#/components/schemas/AdminStatistics"}}},"example":{"success":true,"message":"Admin statistics retrieved successfully","data":{"users":{"totalUsers":1500,"activeUsers":1400,"adminUsers":1200,"guestUsers":300},"companies":{"totalCompanies":1200,"activeCompanies":1150},"ownership":{"totalOwnershipClaims":50,"pendingClaims":10}}}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"403":{"description":"Forbidden - Super admin access required","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/admin/companies/onboarding-summary":{"get":{"summary":"Master company admin counts by account status","tags":["Admin Management"],"security":[{"BearerAuth":[]},{"AppKeyAuth":[]}],"responses":{"200":{"description":"Summary retrieved"}}}},"/admin/companies/workspace/{userId}":{"get":{"summary":"Company workspace for a registered company admin user","tags":["Admin Management"],"security":[{"BearerAuth":[]},{"AppKeyAuth":[]}],"parameters":[{"in":"path","name":"userId","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"Workspace payload (primary user, branches, team)"}}}},"/admin/companies/{companyId}/super-admin-notes":{"patch":{"summary":"Update internal super-admin notes on a company","tags":["Admin Management"],"security":[{"BearerAuth":[]},{"AppKeyAuth":[]}],"parameters":[{"in":"path","name":"companyId","required":true,"schema":{"type":"string"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"superAdminNotes":{"type":"string"}}}}}},"responses":{"200":{"description":"Notes saved"}}}},"/api-key/verify":{"get":{"summary":"Verify API key validity","description":"Verify that an API key is valid and retrieve associated company details.\nUsed by ERP systems to validate their API key before making requests.\n\n**Authentication Required**: API Key + App Key\n\n**Returns**: Company details if API key is valid\n\n**Security**:\n- API key is encrypted and stored securely\n- Validation includes decryption and company ID verification\n- Invalid keys return 401 Unauthorized\n\n**Use Cases**:\n- ERP system startup validation\n- Pre-flight API key check\n- Integration health monitoring\n- API key rotation verification\n\n**Consumption Profile**: ERPs (server-to-server)\n","tags":["API Key Management"],"security":[{"ApiKeyAuth":[]},{"AppKeyAuth":[]}],"parameters":[{"in":"header","name":"x-api-key","required":true,"schema":{"type":"string","example":"U2FsdGVkX1+..."},"description":"API key to verify"},{"in":"header","name":"x-app-key","required":true,"schema":{"type":"string"},"description":"Application key"}],"responses":{"200":{"description":"API key is valid","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"API key is valid"},"data":{"type":"object","properties":{"companyId":{"type":"string","example":"507f1f77bcf86cd799439011"},"companyName":{"type":"string","example":"ABC Electronics Pvt Ltd"},"email":{"type":"string","example":"admin@abcelectronics.com"},"phone_no":{"type":"string","example":"+919876543210"},"gst_no":{"type":"string","example":"27AABCU9603R1ZM"},"pan":{"type":"string","example":"AABCU9603R"},"address":{"type":"object"}}}}}}}},"400":{"description":"API key is required","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"example":{"success":false,"statusCode":400,"message":"API key is required in x-api-key header"}}}},"401":{"description":"Invalid or expired API key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"examples":{"invalidKey":{"summary":"Invalid API key","value":{"success":false,"statusCode":401,"message":"Invalid API key"}},"corruptedKey":{"summary":"Corrupted API key","value":{"success":false,"statusCode":401,"message":"Invalid or corrupted API key"}}}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/api-key/generate":{"post":{"summary":"Generate API key for company","description":"Generate a new API key and secret for the authenticated user's company.\nThis endpoint creates an encrypted API key that can be used for server-to-server authentication.\n\n**Authentication Required**: Yes (JWT Bearer Token)\n\n**Authorization**: Company admin only\n\n**Returns**: API key and secret (shown only once)\n\n**Business Rules**:\n- Only one API key per company\n- If API key already exists, use regenerate endpoint\n- API key is encrypted using AES encryption\n- API secret is SHA256 hash of API key\n- Store both key and secret securely\n\n**Security**:\n- API key contains company ID and timestamp\n- Encrypted with server secret key\n- Cannot be decrypted without server secret\n- Full key shown only once at generation\n\n**Use Cases**:\n- Initial ERP integration setup\n- Enable server-to-server communication\n- Automate transaction uploads\n- API-based data exchange\n\n**Consumption Profile**: Platform (app.swilunify.com)\n","tags":["API Key Management"],"security":[{"BearerAuth":[]},{"AppKeyAuth":[]}],"responses":{"201":{"description":"API key generated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"API key generated successfully"},"data":{"$ref":"#/components/schemas/ApiKeyResponse"},"warning":{"type":"string","example":"Please save your API key and secret securely. You will not be able to see the full key again."}}},"example":{"success":true,"message":"API key generated successfully","data":{"apiKey":"U2FsdGVkX1+...","apiSecret":"a1b2c3d4e5f6...","companyId":"507f1f77bcf86cd799439011","companyName":"ABC Electronics Pvt Ltd","generatedAt":"2024-01-15T10:30:00Z"},"warning":"Please save your API key and secret securely. You will not be able to see the full key again."}}}},"400":{"description":"Company ID not found or API key already exists","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"401":{"description":"Unauthorized - Invalid or missing token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"404":{"description":"Company not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/api-key/regenerate":{"post":{"summary":"Regenerate API key for company","description":"Regenerate API key for the authenticated user's company.\nThis invalidates the old API key and generates a new one.\n\n**Authentication Required**: Yes (JWT Bearer Token)\n\n**Authorization**: Company admin only (must own the company)\n\n**Returns**: New API key and secret (shown only once)\n\n**Business Rules**:\n- Old API key is immediately invalidated\n- All existing integrations must be updated\n- Cannot recover old API key after regeneration\n- Action is logged for audit trail\n\n**Security**:\n- Verifies user owns the company\n- Old key becomes invalid immediately\n- New key uses same encryption method\n- Timestamp updated in encrypted data\n\n**Use Cases**:\n- API key compromised or leaked\n- Security policy requires key rotation\n- Lost API key credentials\n- Regular security maintenance\n\n**Warning**: Update all integrations immediately after regeneration\n\n**Consumption Profile**: Platform (app.swilunify.com)\n","tags":["API Key Management"],"security":[{"BearerAuth":[]},{"AppKeyAuth":[]}],"responses":{"200":{"description":"API key regenerated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"API key regenerated successfully. Please update your integrations with the new key."},"data":{"type":"object","properties":{"apiKey":{"type":"string","example":"U2FsdGVkX1+..."},"apiSecret":{"type":"string","example":"a1b2c3d4e5f6..."},"companyId":{"type":"string","example":"507f1f77bcf86cd799439011"},"companyName":{"type":"string","example":"ABC Electronics Pvt Ltd"},"generatedAt":{"type":"string","format":"date-time","example":"2024-01-15T10:30:00Z"}}},"warning":{"type":"string","example":"The old API key has been invalidated and will no longer work."}}}}}},"400":{"description":"Company ID not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"401":{"description":"Unauthorized - Invalid or missing token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"403":{"description":"Forbidden - User does not own this company","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"example":{"success":false,"statusCode":403,"message":"Unauthorized to regenerate API key for this company"}}}},"404":{"description":"Company not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/api-key/details":{"get":{"summary":"Get API key details","description":"Retrieve API key details for the authenticated user's company.\nReturns masked API key and metadata.\n\n**Authentication Required**: Yes (JWT Bearer Token)\n\n**Authorization**: Company admin only (must own the company)\n\n**Returns**: Masked API key and generation details\n\n**Security**:\n- API key is masked (shows first 8 and last 4 characters)\n- Full key shown only once at generation/regeneration\n- Verifies user owns the company\n\n**Use Cases**:\n- Check if API key exists\n- View API key generation date\n- Verify API key status\n- Integration settings page\n\n**Consumption Profile**: Platform (app.swilunify.com)\n","tags":["API Key Management"],"security":[{"BearerAuth":[]},{"AppKeyAuth":[]}],"responses":{"200":{"description":"API key details retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"API key details retrieved successfully"},"data":{"$ref":"#/components/schemas/ApiKeyDetails"}}},"example":{"success":true,"message":"API key details retrieved successfully","data":{"companyId":"507f1f77bcf86cd799439011","companyName":"ABC Electronics Pvt Ltd","apiKey":"U2FsdGVk...c3d4","fullApiKey":"U2FsdGVkX1+...","generatedAt":"2024-01-15T10:30:00Z","hasApiKey":true}}}}},"400":{"description":"Company ID not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"401":{"description":"Unauthorized - Invalid or missing token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"403":{"description":"Forbidden - User does not own this company","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"example":{"success":false,"statusCode":403,"message":"Unauthorized to view API key for this company"}}}},"404":{"description":"Company or API key not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"examples":{"companyNotFound":{"summary":"Company not found","value":{"success":false,"statusCode":404,"message":"Company not found"}},"apiKeyNotFound":{"summary":"API key not found","value":{"success":false,"statusCode":404,"message":"API key not found for this company"}}}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/api-key/revoke":{"delete":{"summary":"Revoke API key","description":"Permanently revoke the API key for the authenticated user's company.\nThis action cannot be undone.\n\n**Authentication Required**: Yes (JWT Bearer Token)\n\n**Authorization**: Company admin only (must own the company)\n\n**Business Rules**:\n- API key is permanently deleted\n- All integrations using this key will fail\n- Cannot recover revoked API key\n- Must generate new key to re-enable API access\n- Action is logged for audit trail\n\n**Security**:\n- Verifies user owns the company\n- Immediate invalidation\n- No grace period\n\n**Use Cases**:\n- Disable API access permanently\n- Security incident response\n- Decommission integration\n- Company offboarding\n\n**Warning**: This action is permanent and cannot be undone\n\n**Consumption Profile**: Platform (app.swilunify.com)\n","tags":["API Key Management"],"security":[{"BearerAuth":[]},{"AppKeyAuth":[]}],"responses":{"200":{"description":"API key revoked successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"API key revoked successfully"},"data":{"type":"object","properties":{"companyId":{"type":"string","example":"507f1f77bcf86cd799439011"},"companyName":{"type":"string","example":"ABC Electronics Pvt Ltd"}}}}}}}},"400":{"description":"Company ID not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"401":{"description":"Unauthorized - Invalid or missing token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"403":{"description":"Forbidden - User does not own this company","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"example":{"success":false,"statusCode":403,"message":"Unauthorized to revoke API key for this company"}}}},"404":{"description":"Company or API key not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"examples":{"companyNotFound":{"summary":"Company not found","value":{"success":false,"statusCode":404,"message":"Company not found"}},"noApiKey":{"summary":"No API key to revoke","value":{"success":false,"statusCode":404,"message":"No API key found to revoke"}}}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/app-keys":{"post":{"summary":"Create a new app key","tags":["App Keys"],"security":[{"AppKeyAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["developer","name","environment"],"properties":{"developer":{"type":"string","description":"Developer's MongoDB ID"},"name":{"type":"string","description":"Name for the app key"},"environment":{"type":"string","enum":["development","staging","production"],"description":"Environment for the app key"}}}}}},"responses":{"201":{"description":"App key created successfully"},"400":{"description":"Invalid input data"},"401":{"description":"Unauthorized - Invalid token or API key"}}}},"/app-keys/validate":{"get":{"summary":"Validate an app key","description":"Verifies that an application key is registered and active for the given environment.\nUse this from installers, CI, or partner apps before calling authenticated routes.\nNo JWT or other auth headers are required; supply key and environment as query parameters.\n","tags":["App Keys"],"parameters":[{"in":"query","name":"key","required":true,"schema":{"type":"string"},"description":"App key to validate"},{"in":"query","name":"environment","required":true,"schema":{"type":"string","enum":["development","staging","production"]},"description":"Environment to validate against"}],"responses":{"200":{"description":"App key is valid"},"401":{"description":"Invalid app key"}}}},"/app-keys/{id}":{"get":{"summary":"Get app key by ID","tags":["App Keys"],"security":[{"bearerAuth":[]},{"AppKeyAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string"},"description":"App key's MongoDB ID"}],"responses":{"200":{"description":"App key details retrieved successfully"},"401":{"description":"Unauthorized - Invalid token or API key"},"404":{"description":"App key not found"}}}},"/developers/{developerId}/app-keys":{"get":{"summary":"List developer's app keys","tags":["App Keys"],"security":[{"bearerAuth":[]},{"AppKeyAuth":[]}],"parameters":[{"in":"path","name":"developerId","required":true,"schema":{"type":"string"},"description":"Developer's MongoDB ID"}],"responses":{"200":{"description":"List of app keys retrieved successfully"},"401":{"description":"Unauthorized - Invalid token or API key"}}}},"/app-keys/{id}/revoke":{"post":{"summary":"Revoke an app key","tags":["App Keys"],"security":[{"AppKeyAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string"},"description":"App key's MongoDB ID"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["reason"],"properties":{"reason":{"type":"string","description":"Reason for revoking the key"}}}}}},"responses":{"200":{"description":"App key revoked successfully"},"401":{"description":"Unauthorized - Invalid token or API key"},"404":{"description":"App key not found"}}}},"/app-keys/{id}/regenerate":{"post":{"summary":"Regenerate an app key","tags":["App Keys"],"security":[{"AppKeyAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string"},"description":"App key's MongoDB ID"}],"responses":{"200":{"description":"App key regenerated successfully"},"401":{"description":"Unauthorized - Invalid token or API key"},"404":{"description":"App key not found"}}}},"/app-keys/{id}/stats":{"get":{"summary":"Get app key usage statistics","tags":["App Keys"],"security":[{"bearerAuth":[]},{"AppKeyAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string"},"description":"App key's MongoDB ID"}],"responses":{"200":{"description":"Usage statistics retrieved successfully"},"401":{"description":"Unauthorized - Invalid token or API key"},"404":{"description":"App key not found"}}}},"/auth/register":{"post":{"summary":"Register a new user with company details","description":"Register a new user account with associated company information.\nSupports multiple registration scenarios:\n- **Standard Registration**: New user with new company\n- **Referred User**: Sub-user registration via referral token\n- **Multi-Branch**: Branch registration for existing company\n- **Ownership Claim**: Claim ownership of existing company\n\n**Authentication**: None required (public endpoint)\n\n**File Uploads**: Supports document uploads via multipart/form-data\n- gst_certificate: GST registration certificate (PDF/Image)\n- pan_certificate: PAN card document (PDF/Image)\n- ownership_gst_certificate: GST certificate for ownership claim\n- ownership_pan_certificate: PAN certificate for ownership claim\n- profile_img: User profile image\n\n**Data Format**: authData and ownershipData can be sent as:\n- Form fields (JSON string)\n- File uploads (JSON file)\n\n**Business Rules**:\n- Email must be unique across platform\n- GST and PAN must be unique per company\n- SSO verification is performed automatically\n- API key is auto-generated for company\n- Store ID is auto-generated (32 character unique ID)\n","tags":["Authentication"],"requestBody":{"required":true,"content":{"multipart/form-data":{"schema":{"type":"object","required":["authData"],"properties":{"authData":{"type":"string","description":"JSON string containing user registration data.\nMust include: first_name, last_name, email, phone_no\nOptional: companyDetail (nested company data)\n","example":"{\n  \"first_name\": \"John\",\n  \"last_name\": \"Doe\",\n  \"email\": \"john.doe@example.com\",\n  \"phone_no\": \"+919876543210\",\n  \"companyDetail\": {\n    \"company_name\": \"ABC Electronics Pvt Ltd\",\n    \"gst_no\": \"27AABCU9603R1ZM\",\n    \"pan\": \"AABCU9603R\",\n    \"segment\": \"Electronics\",\n    \"vertical\": \"Retail\",\n    \"address\": {\n      \"street_address\": \"123, MG Road\",\n      \"city\": \"Mumbai\",\n      \"state\": \"Maharashtra\",\n      \"country\": \"India\"\n    }\n  }\n}\n"},"ownershipData":{"type":"string","description":"JSON string for ownership claim data (required if isOwnershipClaimed is true)","example":"{\n  \"company_name\": \"XYZ Pharma Ltd\",\n  \"gst_no\": \"27AABCX1234R1ZM\",\n  \"pan\": \"AABCX1234R\",\n  \"email\": \"owner@xyzpharma.com\"\n}\n"},"gst_certificate":{"type":"string","format":"binary","description":"GST registration certificate (PDF/Image)"},"pan_certificate":{"type":"string","format":"binary","description":"PAN card document (PDF/Image)"},"ownership_gst_certificate":{"type":"string","format":"binary","description":"GST certificate for ownership claim"},"ownership_pan_certificate":{"type":"string","format":"binary","description":"PAN certificate for ownership claim"},"profile_img":{"type":"string","format":"binary","description":"User profile image"}}}}}},"responses":{"200":{"description":"User registered successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RegistrationResponse"},"examples":{"standardRegistration":{"summary":"Standard user and company registration","value":{"success":true,"message":"User registered successfully","data":{"user":{"_id":"507f1f77bcf86cd799439011","userName":"John Doe","email":"john.doe@example.com","phone_no":"+919876543210","isActive":true,"assigned_company":{"company_id":"507f1f77bcf86cd799439012","role":"ADMIN"}},"companyDetail":{"_id":"507f1f77bcf86cd799439012","company_name":"ABC Electronics Pvt Ltd","gst_no":"27AABCU9603R1ZM","pan":"AABCU9603R","store_id":"a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6","api_key":"encrypted_api_key_string"},"isMultiBranch":false}}},"multiBranchRegistration":{"summary":"Multi-branch registration","value":{"success":true,"message":"User registered successfully","data":{"user":{"_id":"507f1f77bcf86cd799439013","userName":"Jane Smith","email":"jane.smith@example.com","isActive":false},"companyDetail":{"_id":"507f1f77bcf86cd799439014","company_name":"ABC Electronics - Branch 1","parent_company_id":"507f1f77bcf86cd799439012","alias":"abc-electronics"},"isMultiBranch":true}}}}}}},"400":{"description":"Invalid input or validation error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"examples":{"missingFields":{"summary":"Missing required fields","value":{"success":false,"statusCode":400,"message":"Please provide all required details"}},"duplicateUser":{"summary":"User already exists","value":{"success":false,"statusCode":400,"message":"User already exists"}},"duplicateGST":{"summary":"GST number already taken","value":{"success":false,"statusCode":400,"message":"GST number is already taken"}},"duplicatePAN":{"summary":"PAN number already taken","value":{"success":false,"statusCode":400,"message":"PAN number is already taken"}}}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/auth/login":{"post":{"summary":"Login user with email and password (Basic Auth)","description":"Authenticate user with email and password using Basic Authentication.\nThis endpoint verifies credentials against SSO (Single Sign-On) system\nand returns a JWT token for subsequent authenticated requests.\n\n**Authentication Method**: Basic Auth (Base64 encoded email:password)\n\n**Authorization Header Format**:\n```\nAuthorization: Basic base64(email:password)\n```\n\n**Example**:\n```\nEmail: john.doe@example.com\nPassword: mypassword123\nEncoded: am9obi5kb2VAZXhhbXBsZS5jb206bXlwYXNzd29yZDEyMw==\nHeader: Authorization: Basic am9obi5kb2VAZXhhbXBsZS5jb206bXlwYXNzd29yZDEyMw==\n```\n\n**Login Flow**:\n1. Credentials verified with SSO system\n2. User lookup in SwilUnify database\n3. Account status validation (active/suspended)\n4. Multi-branch handling (if applicable)\n5. JWT token generation\n6. User and company details returned\n\n**Special Cases**:\n- **New User**: If SSO valid but not in database, returns registration prompt\n- **Multi-Branch Pending**: Returns master company details for approval\n- **Suspended Account**: Returns 403 with suspension message\n\n**Consumption Profile**: Platform (swilunify.com)\n","tags":["Authentication"],"security":[{"BasicAuth":[]}],"responses":{"200":{"description":"Login successful or requires additional action","content":{"application/json":{"schema":{"oneOf":[{"$ref":"#/components/schemas/LoginResponse"},{"type":"object","description":"New user requiring registration","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"User is authorized but company details are not completed"},"isCompanyDetail":{"type":"boolean","example":false},"companyInfo":{"type":"object","description":"Pre-filled company information from SSO"},"ssoUserInfo":{"type":"object","description":"SSO user information"}}}]},"examples":{"successfulLogin":{"summary":"Successful login with complete profile","value":{"success":true,"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1MDdmMWY3N2JjZjg2Y2Q3OTk0MzkwMTEiLCJlbWFpbCI6ImpvaG4uZG9lQGV4YW1wbGUuY29tIiwiaWF0IjoxNjMwMDAwMDAwLCJleHAiOjE2MzAwODY0MDB9.abc123","user":{"_id":"507f1f77bcf86cd799439011","email":"john.doe@example.com","userName":"John Doe","phone_no":"+919876543210","companyName":"ABC Electronics Pvt Ltd","companyId":"507f1f77bcf86cd799439012","role":"ADMIN","gst_no":"27AABCU9603R1ZM","pan":"AABCU9603R","isMultiBranch":false}}},"newUserRegistration":{"summary":"New user needs to complete registration","value":{"success":false,"message":"User is authorized but company details are not completed","isCompanyDetail":false,"companyInfo":{"company_name":"XYZ Pharma Ltd","gst_no":"27AABCX1234R1ZM","address":{"city":"Mumbai","state":"Maharashtra"}},"ssoUserInfo":{"username":"Jane Smith","email":"jane.smith@example.com","phone_no":"+919876543211"}}},"multiBranchPending":{"summary":"Multi-branch user pending approval","value":{"isMultiBranch":true,"accountStatus":"PENDING","masterCompanyDetail":{"email":"admin@abcelectronics.com","phone_no":"+912212345678"}}}}}}},"401":{"description":"Invalid credentials or authentication failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"examples":{"invalidCredentials":{"summary":"Invalid email or password","value":{"success":false,"statusCode":401,"message":"Invalid credentials"}},"missingCredentials":{"summary":"Missing authorization header","value":{"success":false,"message":"Authentication failed - No authorization header"}}}}}},"403":{"description":"Account suspended or access denied","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"example":{"success":false,"statusCode":403,"message":"Account suspended. Please contact administrator"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/auth/logout":{"post":{"summary":"Logout current user","description":"Logout the currently authenticated user. This endpoint invalidates\nthe current session. Client should discard the JWT token after logout.\n\n**Authentication Required**: Yes (JWT Bearer Token + App Key)\n\n**Headers Required**:\n- Authorization: Bearer {jwt_token}\n- x-app-key: {app_key}\n\n**Note**: JWT tokens are stateless, so actual invalidation happens\nclient-side by discarding the token. Server-side token blacklisting\ncan be implemented for enhanced security.\n\n**Consumption Profile**: Platform (swilunify.com)\n","tags":["Authentication"],"security":[{"BearerAuth":[]},{"AppKeyAuth":[]}],"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":{"description":"Unauthorized - Invalid or missing token/app key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"examples":{"missingToken":{"summary":"Missing JWT token","value":{"success":false,"statusCode":401,"message":"Access denied. No token provided."}},"missingAppKey":{"summary":"Missing app key","value":{"success":false,"error":"APP key is required"}}}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/auth/admin/login":{"post":{"summary":"Admin/Super user login","description":"Authenticate admin or super user with email and password using Basic Authentication.\nThis endpoint is specifically for SwilUnify platform administrators and\nsuper users who have elevated privileges for system management.\n\n**Authentication Method**: Basic Auth (Base64 encoded email:password)\n\n**User Types**:\n- **ADMINISTRATOR**: Full system access, can manage all companies\n- **USER**: Super user with specific administrative privileges\n\n**Authorization Header Format**:\n```\nAuthorization: Basic base64(email:password)\n```\n\n**Login Flow**:\n1. Credentials verified with SSO system\n2. User lookup in SuperUser collection\n3. Role validation (ADMINISTRATOR or USER)\n4. JWT token generation\n5. ERP token included for SSO integration\n\n**Consumption Profile**: Swil Unify Admin (admin.swilunify.com)\n","tags":["Authentication"],"security":[{"BasicAuth":[]}],"responses":{"200":{"description":"Admin login successful","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"token":{"type":"string","example":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...","description":"JWT token for admin access"},"erpToken":{"type":"string","example":"sso_erp_token_string","description":"SSO ERP token for cross-system authentication"},"user":{"type":"object","properties":{"_id":{"type":"string","example":"507f1f77bcf86cd799439011"},"email":{"type":"string","example":"admin@swilunify.com"},"userName":{"type":"string","example":"Admin User"},"role":{"type":"string","example":"ADMINISTRATOR","enum":["ADMINISTRATOR","USER"]}}}}},"example":{"success":true,"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1MDdmMWY3N2JjZjg2Y2Q3OTk0MzkwMTEiLCJlbWFpbCI6ImFkbWluQHN3aWx1bmlmeS5jb20iLCJyb2xlIjoiQURNSU5JU1RSQVRPUiIsImlhdCI6MTYzMDAwMDAwMCwiZXhwIjoxNjMwMDg2NDAwfQ.xyz789","erpToken":"sso_erp_token_abc123","user":{"_id":"507f1f77bcf86cd799439011","email":"admin@swilunify.com","userName":"Admin User","role":"ADMINISTRATOR"}}}}},"401":{"description":"Invalid credentials or authentication failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"examples":{"invalidCredentials":{"summary":"Invalid email or password","value":{"success":false,"statusCode":401,"message":"Invalid credentials"}},"missingCredentials":{"summary":"Missing authorization header","value":{"success":false,"message":"Authentication failed"}}}}}},"404":{"description":"Admin user not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"example":{"success":false,"statusCode":404,"message":"User not found"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/auth/mr/register":{"post":{"summary":"Register Medical Representative (MR) user","description":"Register a new Medical Representative (Guest User) account.\nMR users have limited access and are typically used for field operations\nin pharmaceutical and healthcare segments.\n\n**User Type**: Guest User (limited privileges)\n\n**Registration Flow**:\n1. Validate required fields\n2. Check for duplicate email\n3. Register with SSO system\n4. Create local user record with 'Guest User' role\n5. Return user details\n\n**OTP Verification**: Email and mobile OTPs should be verified\nbefore calling this endpoint.\n\n**Consumption Profile**: Platform (swilunify.com) - Pharma segment\n","tags":["Authentication"],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["first_name","last_name","email","phone_no","password","emailOtp","mobileOtp"],"properties":{"first_name":{"type":"string","example":"Rajesh","description":"MR's first name"},"last_name":{"type":"string","example":"Kumar","description":"MR's last name"},"email":{"type":"string","format":"email","example":"rajesh.kumar@pharmacompany.com","description":"MR's email address"},"phone_no":{"type":"string","example":"+919876543210","description":"MR's phone number"},"password":{"type":"string","format":"password","example":"SecurePass123!","description":"Account password"},"emailOtp":{"type":"string","example":"123456","description":"Email OTP for verification"},"mobileOtp":{"type":"string","example":"654321","description":"Mobile OTP for verification"}}}}}},"responses":{"200":{"description":"MR user registered successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"MR User created successfully"},"userDetail":{"type":"object","properties":{"_id":{"type":"string","example":"507f1f77bcf86cd799439011"},"userName":{"type":"string","example":"Rajesh Kumar"},"email":{"type":"string","example":"rajesh.kumar@pharmacompany.com"},"role":{"type":"string","example":"Guest User"}}}}}}}},"400":{"description":"Invalid input or validation error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"examples":{"missingFields":{"summary":"Missing required fields","value":{"success":false,"statusCode":400,"message":"Please provide all required details"}},"duplicateUser":{"summary":"User already exists","value":{"success":false,"statusCode":400,"message":"User already exists"}}}}}},"500":{"description":"Internal server error or SSO registration failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"example":{"success":false,"statusCode":500,"message":"Failed to create MR user"}}}}}}},"/auth/mr/login":{"post":{"summary":"Login Medical Representative (MR) user","description":"Authenticate Medical Representative (Guest User) with email and password.\nCredentials are sent as JSON file upload via multipart/form-data.\n\n**User Type**: Guest User\n\n**Authentication Method**: File upload with JSON credentials\n\n**File Format**: The 'data' field should contain a JSON file with:\n```json\n{\n  \"email\": \"rajesh.kumar@pharmacompany.com\",\n  \"password\": \"SecurePass123!\"\n}\n```\n\n**Login Flow**:\n1. Parse credentials from uploaded JSON file\n2. Verify with SSO system\n3. Lookup user with 'Guest User' role\n4. Check if account is active\n5. Generate JWT token\n6. Return token and user details\n\n**Consumption Profile**: Platform (swilunify.com) - Pharma segment\n","tags":["Authentication"],"requestBody":{"required":true,"content":{"multipart/form-data":{"schema":{"type":"object","required":["data"],"properties":{"data":{"type":"string","format":"binary","description":"JSON file containing email and password.\nFile should contain: {\"email\": \"...\", \"password\": \"...\"}\n"}}}}}},"responses":{"200":{"description":"MR login successful","content":{"application/json":{"schema":{"type":"object","properties":{"token":{"type":"string","example":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."},"status":{"type":"string","example":"success"},"user":{"type":"object","properties":{"_id":{"type":"string","example":"507f1f77bcf86cd799439011"},"userName":{"type":"string","example":"Rajesh Kumar"},"email":{"type":"string","example":"rajesh.kumar@pharmacompany.com"},"role":{"type":"string","example":"Guest User"},"isActive":{"type":"boolean","example":true}}}}}}}},"400":{"description":"Invalid input or missing files","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"examples":{"noFiles":{"summary":"No files uploaded","value":{"success":false,"statusCode":400,"message":"No files uploaded"}},"missingCredentials":{"summary":"Missing email or password","value":{"success":false,"statusCode":400,"message":"Please provide email and password"}}}}}},"401":{"description":"Invalid credentials or login failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"examples":{"invalidCredentials":{"summary":"Invalid email or password","value":{"success":false,"statusCode":401,"message":"Invalid credentials"}},"loginFailed":{"summary":"Login failed","value":{"success":false,"statusCode":401,"message":"Login failed"}}}}}},"403":{"description":"User account is blocked","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"example":{"success":false,"statusCode":403,"message":"User is blocked"}}}},"404":{"description":"User not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"example":{"success":false,"statusCode":404,"message":"User not found"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/auth/login/apikey":{"post":{"summary":"Login using API Key (ERP/Server-to-Server Authentication)","description":"Authenticate using Company API Key for server-to-server integrations.\nThis endpoint is specifically designed for ERP systems and external\napplications to authenticate and obtain JWT tokens for API access.\n\n**Authentication Method**: API Key + App Key\n\n**Required Headers**:\n- `x-api-key`: Company-specific API key (obtained during registration)\n- `x-app-key`: Application key (must be \"Swil Unify\" for platform access)\n- `Origin` or `Referer`: Must be from *.swilunify.com domain\n\n**Security Validations**:\n1. **Origin Validation**: Request must originate from *.swilunify.com domain\n2. **App Key Validation**: x-app-key must match \"Swil Unify\" in database\n3. **API Key Validation**: Company API key must be valid and active\n4. **Rate Limiting**: Subject to company-specific rate limits (default: 1000 req/hour)\n5. **Account Status**: Company account must be active\n\n**Use Cases**:\n- ERP systems (SwilERP, LogicERP, Unisolve, Cross)\n- Automated transaction posting\n- Batch report generation\n- Scheduled data synchronization\n- Third-party integrations\n\n**Token Usage**: The returned JWT token should be used for all\nsubsequent API calls in the Authorization header as Bearer token.\n\n**Rate Limiting**: Each company has a configurable rate limit\n(default: 1000 requests/hour). Rate limit resets every hour.\n\n**Consumption Profile**: ERPs (e.g., SwilERP, LogicERP, Unisolve, Cross)\n","tags":["Authentication"],"security":[{"ApiKeyAuth":[]},{"AppKeyAuth":[]}],"parameters":[{"in":"header","name":"x-api-key","required":true,"schema":{"type":"string","example":"U2FsdGVkX1+abc123...encrypted_api_key"},"description":"Company-specific API key (encrypted AES string).\nObtained from company registration or dashboard.\n"},{"in":"header","name":"x-app-key","required":true,"schema":{"type":"string","example":"swil_unify_app_key_xyz789"},"description":"Application key for \"Swil Unify\" platform.\nMust match the registered app key in database.\n"},{"in":"header","name":"Origin","schema":{"type":"string","example":"https://erp.swilunify.com"},"description":"Request origin (automatically sent by browsers).\nMust be from *.swilunify.com domain.\n"}],"responses":{"200":{"description":"API key login successful","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ApiKeyLoginResponse"},"example":{"success":true,"message":"Login successful","token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1MDdmMWY3N2JjZjg2Y2Q3OTk0MzkwMTEiLCJlbWFpbCI6ImNvbXBhbnlAZXhhbXBsZS5jb20iLCJpYXQiOjE2MzAwMDAwMDAsImV4cCI6MTYzMDA4NjQwMH0.abc123","user":{"_id":"507f1f77bcf86cd799439011","email":"company@example.com","userName":"ABC Electronics","phone_no":"+919876543210"},"company":{"name":"ABC Electronics Pvt Ltd","gst_no":"27AABCU9603R1ZM","pan":"AABCU9603R","store_id":"a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6","isMultiBranch":false}}}}},"401":{"description":"Invalid or missing API key/App key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"examples":{"missingApiKey":{"summary":"Missing x-api-key header","value":{"success":false,"message":"API key is required"}},"missingAppKey":{"summary":"Missing x-app-key header","value":{"success":false,"message":"x-app-key header is required"}},"invalidApiKey":{"summary":"Invalid API key","value":{"success":false,"message":"Invalid API key"}},"invalidAppKey":{"summary":"Invalid app key","value":{"success":false,"message":"Invalid app key for Swil Unify"}},"apiKeyValidationFailed":{"summary":"API key validation failed","value":{"success":false,"message":"API key validation failed"}}}}}},"403":{"description":"Forbidden origin or account suspended","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"examples":{"forbiddenOrigin":{"summary":"Request from non-whitelisted domain","value":{"success":false,"message":"Forbidden origin"}},"accountSuspended":{"summary":"Company account suspended","value":{"success":false,"message":"Your account has been suspended temporarily. Please contact the Swil team.","accountSuspended":true}}}}}},"429":{"description":"Rate limit exceeded","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Rate limit exceeded. Maximum 1000 requests per hour allowed."},"resetTime":{"type":"string","format":"date-time","example":"2024-01-15T15:00:00.000Z"}}}}}},"500":{"description":"Internal server error or unable to resolve user","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"example":{"success":false,"statusCode":500,"message":"Unable to resolve user for token issuance"}}}}}}},"/auth/verify-gst":{"post":{"summary":"Verify GST number","description":"Verify the validity of a GST (Goods and Services Tax) number\nusing government GST verification API. This endpoint checks if\nthe GST number is valid, active, and not suspended.\n\n**Authentication Required**: Yes (App Key)\n\n**GST Validation**:\n- Format validation (15 characters alphanumeric)\n- Government database verification\n- Status check (Active/Suspended/Cancelled)\n\n**Use Cases**:\n- Company registration validation\n- Partner onboarding verification\n- Transaction validation\n- Compliance checks\n\n**Note**: This endpoint makes external API call to government\nGST verification service. Response time may vary.\n\n**Consumption Profile**: Platform (swilunify.com)\n","tags":["Authentication"],"security":[{"AppKeyAuth":[]}],"parameters":[{"in":"header","name":"x-app-key","required":true,"schema":{"type":"string"},"description":"Application key for platform identification"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["gstin"],"properties":{"gstin":{"type":"string","example":"27AABCU9603R1ZM","description":"GST Identification Number (GSTIN) to verify.\nMust be 15 characters alphanumeric.\nFormat: 2 digits (state code) + 10 digits (PAN) + 1 digit (entity number) + 1 letter (Z) + 1 check digit\n"}}}}}},"responses":{"200":{"description":"GST verification result","content":{"application/json":{"schema":{"$ref":"#/components/schemas/GSTVerificationResponse"},"examples":{"validGST":{"summary":"Valid and active GST number","value":{"success":true,"message":"GSTIN is Valid"}},"suspendedGST":{"summary":"Suspended GST number","value":{"success":false,"message":"GSTIN is expired"}},"invalidGST":{"summary":"Invalid GST number","value":{"success":false,"message":"GSTIN is invalid"}}}}}},"400":{"description":"Invalid input or missing GST number","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"example":{"success":false,"statusCode":400,"message":"GST number is required"}}}},"401":{"description":"Unauthorized - Missing or invalid app key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"example":{"success":false,"error":"APP key is required"}}}},"500":{"description":"Internal server error or GST API failure","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"example":{"success":false,"statusCode":500,"message":"Internal Server Error"}}}}}}},"/auth/send-otp":{"post":{"summary":"Send OTP to email and phone","description":"Send One-Time Password (OTP) to user's email and phone number for verification\nduring signup process. OTPs are valid for 10 minutes and limited to 3 requests\nper 10 minutes per email/phone combination.\n\n**Rate Limiting**: Maximum 3 OTP requests per 10 minutes\n**OTP Validity**: 10 minutes\n**OTP Length**: 6 digits\n**Storage**: In-memory cache (node-cache)\n\n**Use Cases**:\n- User registration verification\n- Phone number verification\n- Email verification\n\n**Consumption Profile**: Platform (swilunify.com)\n","tags":["Authentication"],"security":[{"AppKeyAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["email","phone_no"],"properties":{"email":{"type":"string","format":"email","example":"john.doe@example.com","description":"User's email address"},"phone_no":{"type":"string","example":"+919876543210","description":"User's phone number with country code"}}}}}},"responses":{"200":{"description":"OTP sent successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"OTP sent to email and phone"},"expiresIn":{"type":"number","example":600,"description":"OTP validity in seconds"}}}}}},"400":{"description":"Invalid input or missing required fields","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"example":{"success":false,"statusCode":400,"message":"Email and phone number are required"}}}},"429":{"description":"Rate limit exceeded","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"statusCode":{"type":"number","example":429},"message":{"type":"string","example":"Too many OTP requests. Please try after 8 minutes"},"timeLeft":{"type":"number","example":480,"description":"Seconds remaining until rate limit resets"}}}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/auth/verify-otp":{"post":{"summary":"Verify OTP","description":"Verify the OTP sent to email and phone. Both OTPs must be correct.\nMaximum 5 verification attempts allowed per OTP.\n\n**Max Attempts**: 5\n**Verification Required**: Both email and phone OTP must match\n**Auto-Expiry**: OTP expires after 10 minutes\n\n**Use Cases**:\n- Complete user registration\n- Verify contact information\n\n**Consumption Profile**: Platform (swilunify.com)\n","tags":["Authentication"],"security":[{"AppKeyAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["email","phone_no","emailOTP","mobileOTP"],"properties":{"email":{"type":"string","format":"email","example":"john.doe@example.com","description":"User's email address"},"phone_no":{"type":"string","example":"+919876543210","description":"User's phone number with country code"},"emailOTP":{"type":"string","example":"123456","description":"6-digit OTP sent to email"},"mobileOTP":{"type":"string","example":"654321","description":"6-digit OTP sent to phone"}}}}}},"responses":{"200":{"description":"OTP verified successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"OTP verified successfully"},"verified":{"type":"boolean","example":true}}}}}},"400":{"description":"Invalid OTP or max attempts exceeded","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"statusCode":{"type":"number","example":400},"message":{"type":"string","example":"Email OTP is invalid, Mobile OTP is invalid"},"remainingAttempts":{"type":"number","example":3,"description":"Number of verification attempts remaining"}}}}}},"404":{"description":"OTP not found or expired","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"example":{"success":false,"statusCode":404,"message":"OTP not found or expired"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/auth/resend-otp":{"post":{"summary":"Resend OTP","description":"Resend OTP to email and phone. Previous OTP will be invalidated.\nSubject to same rate limiting as send-otp endpoint.\n\n**Note**: This will delete the previous OTP and generate new ones.\nAny verification attempts on the old OTP will fail.\n\n**Consumption Profile**: Platform (swilunify.com)\n","tags":["Authentication"],"security":[{"AppKeyAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["email","phone_no"],"properties":{"email":{"type":"string","format":"email","example":"john.doe@example.com","description":"User's email address"},"phone_no":{"type":"string","example":"+919876543210","description":"User's phone number with country code"}}}}}},"responses":{"200":{"description":"OTP resent successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"OTP sent to email and phone"},"expiresIn":{"type":"number","example":600}}}}}},"429":{"description":"Rate limit exceeded","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/companies/profile":{"get":{"summary":"Get company profile","description":"Retrieve the complete profile of the authenticated user's company.\nReturns all company details including business information, documents,\nAPI keys, and multi-branch configuration.\n\n**Authentication Required**: Yes (Bearer Token + App Key)\n\n**Company Identification**: Automatically determined from authenticated user's\nassigned company (req.user.assigned_company.company_id)\n\n**Use Cases**:\n- View company profile in dashboard\n- Pre-fill company data in forms\n- Verify company information\n- Check API key and store ID\n- View uploaded documents\n\n**Consumption Profile**: Platform (swilunify.com)\n","tags":["Company Management"],"security":[{"BearerAuth":[]},{"AppKeyAuth":[]}],"responses":{"200":{"description":"Company profile retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Company profile retrieved successfully"},"data":{"$ref":"#/components/schemas/CompanyProfile"}}},"example":{"success":true,"message":"Company profile retrieved successfully","data":{"_id":"507f1f77bcf86cd799439012","company_name":"ABC Electronics Pvt Ltd","contact_person":"John Doe","contact_person_designation":"Managing Director","gst_no":"27AABCU9603R1ZM","pan":"AABCU9603R","segment":"Electronics","vertical":"Retail","turnover":"10-50 Crores","company_phone_no":"+912212345678","address":{"street_address":"123, MG Road","city":"Mumbai","state":"Maharashtra","country":"India"},"gst_certificate":{"secure_url":"https://storage.example.com/gst_cert.pdf"},"pan_certificate":{"secure_url":"https://storage.example.com/pan_cert.pdf"},"api_key":"U2FsdGVkX1+abc123...encrypted_api_key","store_id":"a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6","isMultiBranch":false}}}}},"401":{"description":"Unauthorized - Invalid or missing token/app key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"examples":{"missingToken":{"summary":"Missing JWT token","value":{"success":false,"statusCode":401,"message":"Access denied. No token provided."}},"missingAppKey":{"summary":"Missing app key","value":{"success":false,"error":"APP key is required"}}}}}},"404":{"description":"Company not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"example":{"success":false,"statusCode":404,"message":"Company not found"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}},"put":{"summary":"Update company profile","description":"Update the authenticated user's company profile including business details\nand document uploads. Supports partial updates - only provided fields\nwill be updated.\n\n**Authentication Required**: Yes (Bearer Token + App Key)\n\n**File Uploads**: Supports document uploads via multipart/form-data\n- profile_img: Company profile/logo image\n- gst_certificate: Updated GST registration certificate\n- pan_certificate: Updated PAN card document\n\n**Data Format**: companyData sent as JSON string or file\n\n**Business Rules**:\n- GST and PAN must be unique (if changed)\n- API key regenerated if GST/PAN changes\n- Files uploaded to Azure Blob Storage\n- Previous documents not automatically deleted\n\n**Use Cases**:\n- Update company contact information\n- Change business address\n- Upload/replace documents\n- Update company profile image\n- Modify turnover or business details\n\n**Consumption Profile**: Platform (swilunify.com)\n","tags":["Company Management"],"security":[{"BearerAuth":[]},{"AppKeyAuth":[]}],"requestBody":{"required":true,"content":{"multipart/form-data":{"schema":{"type":"object","properties":{"companyData":{"type":"string","description":"JSON string containing company data to update.\nAll fields are optional - only provided fields will be updated.\n","example":"{\n  \"company_name\": \"ABC Electronics Pvt Ltd\",\n  \"contact_person\": \"John Doe\",\n  \"contact_person_designation\": \"CEO\",\n  \"company_phone_no\": \"+912212345678\",\n  \"turnover\": \"50-100 Crores\",\n  \"address\": {\n    \"street_address\": \"456, New Road\",\n    \"city\": \"Mumbai\",\n    \"state\": \"Maharashtra\",\n    \"country\": \"India\"\n  }\n}\n"},"profile_img":{"type":"string","format":"binary","description":"Company profile/logo image (JPEG, PNG)"},"gst_certificate":{"type":"string","format":"binary","description":"GST registration certificate (PDF/Image)"},"pan_certificate":{"type":"string","format":"binary","description":"PAN card document (PDF/Image)"}}}}}},"responses":{"200":{"description":"Company profile updated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Company profile updated successfully"},"data":{"$ref":"#/components/schemas/CompanyProfile"}}}}}},"400":{"description":"Invalid input data or duplicate GST/PAN","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"examples":{"noFiles":{"summary":"No files uploaded","value":{"success":false,"statusCode":400,"message":"No files uploaded"}},"duplicateGST":{"summary":"GST already taken","value":{"success":false,"statusCode":400,"message":"GSTIN is already taken"}},"duplicatePAN":{"summary":"PAN already taken","value":{"success":false,"statusCode":400,"message":"PAN is already taken"}}}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"404":{"description":"Company not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/companies/search":{"get":{"summary":"Search companies by name, GST, or PAN","description":"Search for companies in the platform using company name, GST number, or PAN.\nReturns basic company information with pagination support.\n\n**Authentication Required**: Yes (Bearer Token + App Key)\n\n**Search Criteria**: At least one search parameter is required\n- company_name: Partial match (case-insensitive, starts with)\n- gstin: Exact match\n- pan: Exact match\n\n**Use Cases**:\n- Find business partners\n- Verify company existence\n- Search for transaction recipients\n- Lookup company details\n- Auto-complete company selection\n\n**Consumption Profile**: Platform (swilunify.com)\n","tags":["Company Management"],"security":[{"BearerAuth":[]},{"AppKeyAuth":[]}],"parameters":[{"in":"query","name":"company_name","schema":{"type":"string","example":"ABC Electronics"},"description":"Company name to search (partial match, case-insensitive)"},{"in":"query","name":"gstin","schema":{"type":"string","example":"27AABCU9603R1ZM"},"description":"GST number to search (exact match)"},{"in":"query","name":"pan","schema":{"type":"string","example":"AABCU9603R"},"description":"PAN number to search (exact match)"},{"in":"query","name":"page","schema":{"type":"integer","default":1,"minimum":1},"description":"Page number for pagination"},{"in":"query","name":"limit","schema":{"type":"integer","default":10,"minimum":1,"maximum":100},"description":"Number of results per page"}],"responses":{"200":{"description":"Companies retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Companies retrieved successfully"},"data":{"type":"object","properties":{"companyNames":{"type":"array","items":{"$ref":"#/components/schemas/CompanySearchResult"}},"pagination":{"type":"object","properties":{"page":{"type":"integer","example":1},"limit":{"type":"integer","example":10},"total":{"type":"integer","example":5}}}}}}},"example":{"success":true,"message":"Companies retrieved successfully","data":{"companyNames":[{"company_name":"ABC Electronics Pvt Ltd","gst_no":"27AABCU9603R1ZM","pan":"AABCU9603R","station":"Mumbai"},{"company_name":"ABC Electronics - Branch 1","gst_no":"27AABCU9603R1ZM","pan":"AABCU9603R","station":"Pune"}],"pagination":{"page":1,"limit":10,"total":2}}}}}},"400":{"description":"Invalid search criteria - no search parameters provided","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"example":{"success":false,"statusCode":400,"message":"Please provide search criteria"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/companies/branches":{"post":{"summary":"Create a branch (child company + branch admin user)","description":"Creates a new branch under the authenticated master company.\nBody may be `{ branch: { name, code, type, gstin, address, contact, additionalDetails } }`\nor the same fields at the top level.\n","tags":["Company Management"],"security":[{"BearerAuth":[]},{"AppKeyAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"201":{"description":"Branch created successfully"},"400":{"description":"Validation error"},"401":{"description":"Unauthorized"},"403":{"description":"Only master company can create branches"},"500":{"description":"Internal server error"}}},"get":{"summary":"Get company branches","description":"Retrieve all branches (child companies) of the authenticated user's company.\nOnly returns branches where the current company is the parent.\n\n**Authentication Required**: Yes (Bearer Token + App Key)\n\n**Parent Company**: Automatically determined from authenticated user's company\n\n**Returns**: List of branches with user details and account status\n\n**Use Cases**:\n- View all company branches\n- Manage branch access\n- Monitor branch status\n- Review branch users\n- Approve/reject branch requests\n\n**Consumption Profile**: Platform (swilunify.com)\n","tags":["Company Management"],"security":[{"BearerAuth":[]},{"AppKeyAuth":[]}],"responses":{"200":{"description":"Branches retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Branches retrieved successfully"},"data":{"type":"array","items":{"$ref":"#/components/schemas/BranchInfo"}}}},"example":{"success":true,"message":"Branches retrieved successfully","data":[{"company_name":"ABC Electronics - Branch 1","gst_no":"27AABCU9603R1ZM","pan":"AABCU9603R","address":{"street_address":"789, Branch Road","city":"Pune","state":"Maharashtra","country":"India"},"parent_company_id":"507f1f77bcf86cd799439012","userDetail":{"userName":"Jane Smith","email":"jane.smith@abcelectronics.com","phone_no":"+919876543211","isActive":true,"accountStatus":"APPROVED"}},{"company_name":"ABC Electronics - Branch 2","gst_no":"27AABCU9603R1ZM","pan":"AABCU9603R","address":{"street_address":"321, Another Road","city":"Bangalore","state":"Karnataka","country":"India"},"parent_company_id":"507f1f77bcf86cd799439012","userDetail":{"userName":"Bob Johnson","email":"bob.johnson@abcelectronics.com","phone_no":"+919876543212","isActive":false,"accountStatus":"PENDING"}}]}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/companies/branches/{id}":{"patch":{"summary":"Update branch status (Approve/Suspend)","description":"Update the status of a branch user - approve or suspend branch access.\nOnly parent company admins can update branch status.\n\n**Authentication Required**: Yes (Bearer Token + App Key)\n\n**Authorization**: Must be parent company admin\n\n**Status Updates**:\n- isSuspend: true → Activates branch (APPROVED status)\n- isSuspend: false → Suspends branch (REJECTED status)\n\n**Use Cases**:\n- Approve new branch registration\n- Suspend misbehaving branch\n- Reactivate suspended branch\n- Manage branch access control\n\n**Consumption Profile**: Platform (swilunify.com)\n","tags":["Company Management"],"security":[{"BearerAuth":[]},{"AppKeyAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","example":"507f1f77bcf86cd799439011"},"description":"Branch user ID (MongoDB ObjectId)"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["isSuspend"],"properties":{"isSuspend":{"type":"boolean","description":"true: Approve/Activate branch (set isActive=true, accountStatus=APPROVED)\nfalse: Suspend/Reject branch (set isActive=false, accountStatus=REJECTED)\n","example":true}}}}}},"responses":{"200":{"description":"Branch updated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Branch updated successfully"},"data":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Branch updated successfully"}}}}},"example":{"success":true,"message":"Branch updated successfully","data":{"success":true,"message":"Branch updated successfully"}}}}},"400":{"description":"Invalid input data","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"404":{"description":"Branch user not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"example":{"success":false,"statusCode":404,"message":"User not found"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/companies/check-alias":{"post":{"summary":"Check if company alias exists","description":"Check if a company alias is already taken by another company.\nUsed during multi-branch registration to ensure unique aliases.\n\n**Authentication Required**: Yes (Bearer Token + App Key)\n\n**Alias Format**: Lowercase alphanumeric, typically derived from company name\n\n**Use Cases**:\n- Validate alias during branch registration\n- Check alias availability\n- Prevent duplicate aliases\n- Auto-generate unique aliases\n\n**Consumption Profile**: Platform (swilunify.com)\n","tags":["Company Management"],"security":[{"BearerAuth":[]},{"AppKeyAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["alias"],"properties":{"alias":{"type":"string","example":"abc-electronics","description":"Company alias to check (case-insensitive)"}}}}}},"responses":{"200":{"description":"Alias check completed","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Alias check completed"},"data":{"type":"object","properties":{"isAlreadyAliasExist":{"type":"boolean","example":false}}}}},"examples":{"aliasAvailable":{"summary":"Alias is available","value":{"success":true,"message":"Alias check completed","data":{"isAlreadyAliasExist":false}}},"aliasTaken":{"summary":"Alias already exists","value":{"success":true,"message":"Alias check completed","data":{"isAlreadyAliasExist":true}}}}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/companies/linked":{"post":{"summary":"Get linked companies (Multi-branch or Ownership claims)","description":"Retrieve companies linked to the specified company through GST/PAN matching.\nUsed to find multi-branch companies or ownership claim conflicts.\n\n**Authentication Required**: Yes (Bearer Token + App Key)\n\n**Linking Logic**:\n- Matches companies with same GST or PAN\n- Filters by isMultiBranch flag\n- Excludes the queried company itself\n- Returns companies with ownership claims\n\n**Use Cases**:\n- Find all branches of a parent company\n- Identify ownership claim conflicts\n- Verify multi-branch relationships\n- Manage company hierarchies\n\n**Consumption Profile**: Platform (swilunify.com)\n","tags":["Company Management"],"security":[{"BearerAuth":[]},{"AppKeyAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["isMultiBranch","id"],"properties":{"isMultiBranch":{"type":"boolean","description":"Filter for multi-branch companies","example":true},"id":{"type":"string","description":"Company ID to search for linked companies","example":"507f1f77bcf86cd799439012"}}}}}},"responses":{"200":{"description":"Linked companies retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Linked companies retrieved successfully"},"data":{"type":"object","properties":{"linkedCompanies":{"type":"array","items":{"type":"object","properties":{"_id":{"type":"string"},"company_name":{"type":"string"},"accountStatus":{"type":"string"},"user_id":{"type":"string"},"ownershipClaimed":{"type":"boolean"},"isAnotherCompanyClaiming":{"type":"boolean"}}}}}}}},"example":{"success":true,"message":"Linked companies retrieved successfully","data":{"linkedCompanies":[{"_id":"507f1f77bcf86cd799439013","company_name":"ABC Electronics - Branch 1","accountStatus":"APPROVED","user_id":"507f1f77bcf86cd799439014","ownershipClaimed":true,"isAnotherCompanyClaiming":false}]}}}}},"400":{"description":"Invalid input data","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"404":{"description":"Company not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"example":{"success":false,"statusCode":404,"message":"Company not found"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/companies/statistics":{"get":{"summary":"Get company statistics","description":"Retrieve platform-wide company statistics and analytics.\nProvides insights into total companies, active status, multi-branch\ndistribution, and document completion rates.\n\n**Authentication Required**: Yes (Bearer Token + App Key)\n\n**Statistics Included**:\n- Total companies registered\n- Active companies (not claiming ownership)\n- Multi-branch companies\n- Companies with GST registration\n- Companies with PAN registration\n\n**Use Cases**:\n- Admin dashboard analytics\n- Platform health monitoring\n- Business intelligence reports\n- Compliance tracking\n- Growth metrics\n\n**Consumption Profile**: Platform (swilunify.com), Admin (admin.swilunify.com)\n","tags":["Company Management"],"security":[{"BearerAuth":[]},{"AppKeyAuth":[]}],"responses":{"200":{"description":"Company statistics retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Company statistics retrieved successfully"},"data":{"$ref":"#/components/schemas/CompanyStatistics"}}},"example":{"success":true,"message":"Company statistics retrieved successfully","data":{"totalCompanies":1500,"activeCompanies":1450,"multiBranchCompanies":250,"companiesWithGST":1400,"companiesWithPAN":1500}}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/companies/advanced-search":{"get":{"summary":"Advanced company search with multiple filters","description":"Perform advanced search for companies with multiple filter criteria\nand sorting options. Supports pagination and returns detailed company\ninformation including user details.\n\n**Authentication Required**: Yes (Bearer Token + App Key)\n\n**Filter Options**:\n- company_name: Partial match (case-insensitive)\n- gst_no: Exact match\n- pan: Exact match\n- status: Active status (true/false)\n- isMultiBranch: Multi-branch filter (true/false)\n- parent_company_id: Parent company filter\n\n**Sorting**: Configurable by field and order\n\n**Use Cases**:\n- Admin company management\n- Compliance reporting\n- Data export and analysis\n- Multi-branch hierarchy view\n- Partner discovery\n\n**Consumption Profile**: Platform (swilunify.com), Admin (admin.swilunify.com)\n","tags":["Company Management"],"security":[{"BearerAuth":[]},{"AppKeyAuth":[]}],"parameters":[{"in":"query","name":"company_name","schema":{"type":"string","example":"ABC Electronics"},"description":"Company name filter (partial match, case-insensitive)"},{"in":"query","name":"gst_no","schema":{"type":"string","example":"27AABCU9603R1ZM"},"description":"GST number filter (exact match)"},{"in":"query","name":"pan","schema":{"type":"string","example":"AABCU9603R"},"description":"PAN number filter (exact match)"},{"in":"query","name":"status","schema":{"type":"boolean","example":true},"description":"Active status filter (true=active, false=inactive)"},{"in":"query","name":"isMultiBranch","schema":{"type":"boolean","example":false},"description":"Multi-branch filter (true=multi-branch, false=single)"},{"in":"query","name":"parent_company_id","schema":{"type":"string","example":"507f1f77bcf86cd799439012"},"description":"Parent company ID filter (null for parent companies)"},{"in":"query","name":"page","schema":{"type":"integer","default":1,"minimum":1},"description":"Page number for pagination"},{"in":"query","name":"limit","schema":{"type":"integer","default":20,"minimum":1,"maximum":100},"description":"Number of results per page"},{"in":"query","name":"sortBy","schema":{"type":"string","default":"createdAt","enum":["createdAt","company_name","gst_no","pan"]},"description":"Field to sort by"},{"in":"query","name":"sortOrder","schema":{"type":"integer","default":-1,"enum":[1,-1]},"description":"Sort order (1=ascending, -1=descending)"}],"responses":{"200":{"description":"Companies retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Companies retrieved successfully"},"data":{"type":"object","properties":{"companies":{"type":"array","items":{"type":"object","properties":{"_id":{"type":"string"},"company_name":{"type":"string"},"gst_no":{"type":"string"},"pan":{"type":"string"},"address":{"type":"object"},"isMultiBranch":{"type":"boolean"},"parent_company_id":{"type":"string"},"isAnotherCompanyClaiming":{"type":"boolean"},"createdAt":{"type":"string","format":"date-time"},"userDetail":{"type":"object","properties":{"userName":{"type":"string"},"email":{"type":"string"},"isActive":{"type":"boolean"},"accountStatus":{"type":"string"}}}}}},"pagination":{"type":"object","properties":{"page":{"type":"integer"},"limit":{"type":"integer"},"total":{"type":"integer"},"pages":{"type":"integer"}}}}}}},"example":{"success":true,"message":"Companies retrieved successfully","data":{"companies":[{"_id":"507f1f77bcf86cd799439012","company_name":"ABC Electronics Pvt Ltd","gst_no":"27AABCU9603R1ZM","pan":"AABCU9603R","address":{"street_address":"123, MG Road","city":"Mumbai","state":"Maharashtra","country":"India"},"isMultiBranch":false,"isAnotherCompanyClaiming":false,"createdAt":"2024-01-15T10:30:00.000Z","userDetail":{"userName":"John Doe","email":"john.doe@abcelectronics.com","isActive":true,"accountStatus":"APPROVED"}}],"pagination":{"page":1,"limit":20,"total":1,"pages":1}}}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/csv-definitions":{"get":{"summary":"List CSV definitions (company scoped)","tags":["CSV Definitions V2"],"security":[{"bearerAuth":[]}],"parameters":[{"in":"query","name":"page","schema":{"type":"integer","default":1}},{"in":"query","name":"limit","schema":{"type":"integer","default":20}},{"in":"query","name":"isHtf","schema":{"type":"boolean"}},{"in":"query","name":"search","schema":{"type":"string"}},{"in":"query","name":"isDefault","schema":{"type":"boolean"}}],"responses":{"200":{"description":"List of CSV definitions","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CsvDefinitionsListResponse"}}}}}},"post":{"summary":"Create a CSV definition","tags":["CSV Definitions V2"],"security":[{"bearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/CsvDefinition"}],"required":["is_htf_format"]}}}},"responses":{"200":{"description":"Created","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CsvDefinitionResponse"}}}}}}},"/csv-definitions/resolve":{"get":{"summary":"Resolve effective CSV definition for export/import","tags":["CSV Definitions V2"],"security":[{"bearerAuth":[]}],"parameters":[{"in":"query","name":"format","required":true,"schema":{"type":"string","enum":["structured","flat"]}},{"in":"query","name":"headerNames","schema":{"type":"string"},"description":"JSON array or CSV string of headers (flat only)"}],"responses":{"200":{"description":"Active/effective mapping for the company","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CsvDefinitionResponse"}}}}}}},"/csv-definitions/detect":{"post":{"summary":"Upload a CSV file to detect matching CSV definition","description":"Parses headers (flat first row, or HTF H-row after row marker) and scores flat + HTF definitions.","tags":["CSV Definitions V2"],"security":[{"bearerAuth":[]}],"requestBody":{"required":true,"content":{"multipart/form-data":{"schema":{"type":"object","properties":{"file":{"type":"string","format":"binary"}}}}}},"responses":{"200":{"description":"Detection result with best match (if any) and parsed headers","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CsvDetectResponse"}}}}}}},"/csv-definitions/{id}":{"get":{"summary":"Get a CSV definition by ID","tags":["CSV Definitions V2"],"security":[{"bearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"CSV definition","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CsvDefinitionResponse"}}}}}},"put":{"summary":"Update a CSV definition","tags":["CSV Definitions V2"],"security":[{"bearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CsvDefinition"}}}},"responses":{"200":{"description":"Updated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CsvDefinitionResponse"}}}}}},"delete":{"summary":"Delete a CSV definition","tags":["CSV Definitions V2"],"security":[{"bearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"Deleted","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"message":{"type":"string"},"data":{"type":"object","properties":{"_id":{"type":"string"}}}}}}}}}}},"/dashboard/transactions":{"get":{"summary":"Get user transaction statistics","description":"Retrieve comprehensive transaction statistics for the authenticated user's company for a specific fiscal year","tags":["Dashboard"],"security":[{"bearerAuth":[]}],"parameters":[{"in":"query","name":"year","schema":{"type":"integer","minimum":2000,"maximum":2030},"description":"Fiscal year start (4-digit year). If not provided, uses current fiscal year","example":2024}],"responses":{"200":{"description":"Transaction statistics retrieved successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/DashboardStatsResponse"},"example":{"success":true,"message":"Transaction statistics retrieved successfully","data":{"transactionCount":150,"purchaseInvoiceLength":25,"salesOrderLength":30,"purchaseChallanLength":15,"salesReturnLength":5,"salesInvoiceLength":40,"purchaseOrderLength":20,"salesChallanLength":10,"purchaseReturnLength":5,"purchaseInvoiceDownloaded":20,"purchaseInvoiceNotDownloaded":5,"salesOrderDownloaded":25,"salesOrderNotDownloaded":5,"purchaseChallanDownloaded":12,"purchaseChallanNotDownloaded":3,"salesReturnDownloaded":4,"salesReturnNotDownloaded":1,"salesInvoiceDownloaded":35,"salesInvoiceNotDownloaded":5,"purchaseOrderDownloaded":18,"purchaseOrderNotDownloaded":2,"salesChallanDownloaded":8,"salesChallanNotDownloaded":2,"purchaseReturnDownloaded":4,"purchaseReturnNotDownloaded":1}}}}},"400":{"description":"Bad request - Invalid year parameter","content":{"application/json":{"schema":{"$ref":"#/components/schemas/StandardError"},"example":{"success":false,"statusCode":400,"message":"Invalid year parameter. Please provide a valid 4-digit fiscal year start."}}}},"401":{"description":"Unauthorized - Invalid or missing authentication token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/StandardError"}}}},"404":{"description":"Not found - Company details not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/StandardError"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/StandardError"}}}}}}},"/dashboard/graph":{"get":{"summary":"Get transaction graph data","description":"Retrieve monthly transaction data for dashboard graphs and analytics for a specific fiscal year","tags":["Dashboard"],"security":[{"bearerAuth":[]}],"parameters":[{"in":"query","name":"year","schema":{"type":"integer","minimum":2000,"maximum":2030},"description":"Fiscal year start (4-digit year). If not provided, uses current fiscal year","example":2024}],"responses":{"200":{"description":"Transaction graph data retrieved successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/DashboardGraphResponse"},"example":{"success":true,"message":"Transaction graph data retrieved successfully","data":{"graphData":[{"month":"April","data":{"total_transactions":25,"total_sent":15,"total_received":10,"sales_invoice":8,"purchase_invoice":6,"sales_order":4,"purchase_order":7}},{"month":"May","data":{"total_transactions":32,"total_sent":19,"total_received":13,"sales_invoice":10,"purchase_invoice":8,"sales_order":5,"purchase_order":9}}],"year":2024,"queryMethod":"optimized_aggregation","dataPoints":{"sender":24,"receiver":18,"total":42}}}}}},"400":{"description":"Bad request - Invalid year parameter","content":{"application/json":{"schema":{"$ref":"#/components/schemas/StandardError"},"example":{"success":false,"statusCode":400,"message":"Invalid year parameter. Please provide a valid 4-digit fiscal year start."}}}},"401":{"description":"Unauthorized - Invalid or missing authentication token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/StandardError"}}}},"404":{"description":"Not found - Company details not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/StandardError"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/StandardError"}}}}}}},"/developers":{"post":{"summary":"Create a new developer","tags":["Developers"],"security":[{"AppKeyAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["name","company"],"properties":{"name":{"type":"string","description":"Developer's full name"},"email":{"type":"string","format":"email","description":"Developer's email address"},"company":{"type":"string","description":"Company name"},"phone":{"type":"string","description":"Contact phone number"},"website":{"type":"string","description":"Company website"},"integrationPurpose":{"type":"string","description":"Purpose of API integration"}}}}}},"responses":{"201":{"description":"Developer created successfully"},"400":{"description":"Invalid input data"},"401":{"description":"Unauthorized - Invalid token or API key"}}},"get":{"summary":"List all developers","tags":["Developers"],"security":[{"bearerAuth":[]},{"AppKeyAuth":[]}],"parameters":[{"in":"query","name":"status","schema":{"type":"string","enum":["active","inactive","suspended"]},"description":"Filter by developer status"},{"in":"query","name":"company","schema":{"type":"string"},"description":"Filter by company name (partial match)"}],"responses":{"200":{"description":"List of developers retrieved successfully"},"401":{"description":"Unauthorized - Invalid token or API key"}}}},"/developers/{id}":{"get":{"summary":"Get developer by ID","tags":["Developers"],"security":[{"bearerAuth":[]},{"AppKeyAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string"},"description":"Developer's MongoDB ID"}],"responses":{"200":{"description":"Developer details retrieved successfully"},"401":{"description":"Unauthorized - Invalid token or API key"},"404":{"description":"Developer not found"}}},"put":{"summary":"Update developer details","tags":["Developers"],"security":[{"AppKeyAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string"},"description":"Developer's MongoDB ID"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string"},"company":{"type":"string"},"phone":{"type":"string"},"website":{"type":"string"},"integrationPurpose":{"type":"string"}}}}}},"responses":{"200":{"description":"Developer updated successfully"},"400":{"description":"Invalid input data"},"401":{"description":"Unauthorized - Invalid token or API key"},"404":{"description":"Developer not found"}}},"delete":{"summary":"Delete a developer","tags":["Developers"],"security":[{"AppKeyAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string"},"description":"Developer's MongoDB ID"}],"responses":{"200":{"description":"Developer deleted successfully"},"401":{"description":"Unauthorized - Invalid token or API key"},"404":{"description":"Developer not found"}}}},"/developers/email":{"get":{"summary":"Get developer by email","tags":["Developers"],"security":[{"bearerAuth":[]},{"AppKeyAuth":[]}],"parameters":[{"in":"query","name":"email","required":true,"schema":{"type":"string"},"description":"Developer's email address"}],"responses":{"200":{"description":"Developer details retrieved successfully"},"401":{"description":"Unauthorized - Invalid token or API key"},"404":{"description":"Developer not found"}}}},"/developers/{id}/status":{"patch":{"summary":"Update developer status","tags":["Developers"],"security":[{"AppKeyAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string"},"description":"Developer's MongoDB ID"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["status"],"properties":{"status":{"type":"string","enum":["active","inactive","suspended"]}}}}}},"responses":{"200":{"description":"Developer status updated successfully"},"400":{"description":"Invalid status value"},"401":{"description":"Unauthorized - Invalid token or API key"},"404":{"description":"Developer not found"}}}},"/mails":{"get":{"tags":["Mail"],"summary":"List mails for current user/company","security":[{"AppKeyAuth":[]},{"bearerAuth":[]}],"responses":{"200":{"description":"Mails fetched successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/MailListResponse"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/StandardError"}}}},"500":{"description":"Server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/StandardError"}}}}}}},"/mails/{id}/read":{"patch":{"tags":["Mail"],"summary":"Mark a mail as read","security":[{"AppKeyAuth":[]},{"bearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"Mail marked as read","content":{"application/json":{"schema":{"$ref":"#/components/schemas/MailMutationResponse"}}}},"400":{"description":"Bad request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/StandardError"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/StandardError"}}}}}}},"/mails/{id}":{"delete":{"tags":["Mail"],"summary":"Delete a mail","security":[{"AppKeyAuth":[]},{"bearerAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"Mail deleted","content":{"application/json":{"schema":{"$ref":"#/components/schemas/MailMutationResponse"}}}},"401":{"description":"Unauthorized","content":{"application/json":{"schema":{"$ref":"#/components/schemas/StandardError"}}}}}}},"/masters/{type}":{"get":{"summary":"Get master data by type","description":"Returns the single master array stored per document for the requested type.","tags":["Masters"],"parameters":[{"in":"path","name":"type","required":true,"schema":{"$ref":"#/components/schemas/MastersType"},"description":"Master data type to fetch"}],"responses":{"200":{"description":"Master data fetched successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/MastersGetResponse"}}}},"400":{"description":"Invalid master type","content":{"application/json":{"schema":{"$ref":"#/components/schemas/StandardError"}}}},"500":{"description":"Server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/StandardError"}}}}}},"put":{"summary":"Replace master data array by type (Super Admin only)","tags":["Masters"],"security":[{"bearerAuth":[]}],"parameters":[{"in":"path","name":"type","required":true,"schema":{"$ref":"#/components/schemas/MastersType"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"items":{"type":"array","items":{"type":"object"}}}}}}},"responses":{"200":{"description":"Master data saved successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/MastersMutationResponse"}}}},"400":{"description":"Invalid input or master type","content":{"application/json":{"schema":{"$ref":"#/components/schemas/StandardError"}}}},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"500":{"description":"Server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/StandardError"}}}}}},"delete":{"summary":"Clear master data array by type (Super Admin only)","tags":["Masters"],"security":[{"bearerAuth":[]}],"parameters":[{"in":"path","name":"type","required":true,"schema":{"$ref":"#/components/schemas/MastersType"}}],"responses":{"200":{"description":"Master data cleared successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/MastersMutationResponse"}}}},"400":{"description":"Invalid master type","content":{"application/json":{"schema":{"$ref":"#/components/schemas/StandardError"}}}},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"500":{"description":"Server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/StandardError"}}}}}}},"/reports":{"post":{"summary":"Create a new report","description":"Multipart upload. Send reportDetails, documentDetails, ShareLinkID, optional receiver, optional mailImportData,\nplus file field document and optional attachments. Complex objects may be sent as JSON strings.\nAuth: Bearer token or x-api-key and x-app-key.\n","tags":["Reports"],"security":[{"bearerAuth":[]},{"ApiKeyAuth":[]},{"AppKeyAuth":[]}],"requestBody":{"required":true,"content":{"multipart/form-data":{"schema":{"type":"object","properties":{"reportDetails":{"type":"object","description":"Report metadata (may be sent as JSON string by clients)."},"documentDetails":{"type":"object","description":"Includes document base64 and documentType (may be JSON string)."},"ShareLinkID":{"type":"string"},"receiver":{"type":"object","description":"Receiver party (may be JSON string)."},"mailImportData":{"type":"object","description":"When set, mail import path; other fields may be omitted."},"document":{"type":"string","format":"binary","description":"Uploaded file (field name document)"},"attachments":{"type":"array","items":{"type":"string","format":"binary"}}}}}}},"responses":{"200":{"description":"Report created or updated (deduped by service rules)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SuccessReport"}}}},"400":{"description":"Missing/invalid body (e.g. `Please provide all necessary details`), validation, or business rule\n(e.g. discontinued MR user — see service).\n","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsControllerError"}}}},"401":{"description":"Missing/invalid JWT; missing/invalid `x-api-key` or `x-app-key`; or user could not be resolved for API key.\n","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsHttp401"}}}},"403":{"description":"Company/account suspended (API key validation) or deactivated user (JWT).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsHttp403"}}}},"429":{"description":"API key hourly rate limit exceeded (validateApiKey).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsHttp429"}}}},"500":{"description":"Server or Azure upload error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsHttp500"}}}}}},"get":{"summary":"Get reports with filters and pagination","description":"List reports for the authenticated user. Guest or MR mode uses isMrUser filter. Company users need assigned_company for non-guest paths (400 Company assignment is required if missing).","tags":["Reports"],"security":[{"bearerAuth":[]},{"ApiKeyAuth":[]},{"AppKeyAuth":[]}],"parameters":[{"in":"query","name":"isMrUser","schema":{"type":"string"},"description":"Filter by MR / guest user type (see `ROLES` in app)."},{"in":"query","name":"report_name","schema":{"type":"string"},"description":"Filter by report name"},{"in":"query","name":"report_date","schema":{"type":"string","format":"date"},"description":"Filter by report date"},{"in":"query","name":"offset","schema":{"type":"integer","default":0},"description":"Page offset (page size is fixed in service, typically 20)"},{"in":"query","name":"isSentReports","schema":{"type":"string","enum":[true,false]},"description":"Filter by sent vs received reports"}],"responses":{"200":{"description":"Reports retrieved successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PaginatedReportsResponse"}}}},"400":{"description":"Company assignment required for this filter mode","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsControllerError"}}}},"401":{"description":"Not authenticated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsHttp401"}}}},"500":{"description":"Server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsHttp500"}}}}}}},"/reports/search":{"get":{"summary":"Search reports with advanced filters","description":"Same visibility rules as other search endpoints; results are limited to reports where the user is sender or receiver. Supports pagination and filters by type, file type, date range, and emails.","tags":["Reports"],"security":[{"bearerAuth":[]},{"ApiKeyAuth":[]},{"AppKeyAuth":[]}],"parameters":[{"in":"query","name":"reportType","schema":{"type":"string"},"description":"Filter by report type"},{"in":"query","name":"fileType","schema":{"type":"string","enum":["pdf","csv"]},"description":"Filter by file type"},{"in":"query","name":"dateFrom","schema":{"type":"string","format":"date"},"description":"Filter by start date"},{"in":"query","name":"dateTo","schema":{"type":"string","format":"date"},"description":"Filter by end date"},{"in":"query","name":"senderEmail","schema":{"type":"string"},"description":"Filter by sender email"},{"in":"query","name":"receiverEmail","schema":{"type":"string"},"description":"Filter by receiver email"},{"in":"query","name":"reportName","schema":{"type":"string"},"description":"Filter by report name"},{"in":"query","name":"page","schema":{"type":"integer","default":1},"description":"Page number"},{"in":"query","name":"limit","schema":{"type":"integer","default":20},"description":"Items per page"}],"responses":{"200":{"description":"Search completed; `data` is the current page; `pagination` includes total and page count","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PaginatedReportsResponse"}}}},"401":{"description":"Not authenticated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsHttp401"}}}},"500":{"description":"Server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsHttp500"}}}}}}},"/reports/recent":{"get":{"summary":"Get recent reports","description":"Uses search with page 1 and the given `limit`; returns `data` array without separate pagination object in response (pagination still computed internally).","tags":["Reports"],"security":[{"bearerAuth":[]},{"ApiKeyAuth":[]},{"AppKeyAuth":[]}],"parameters":[{"in":"query","name":"limit","schema":{"type":"integer","default":10},"description":"Max reports to return"}],"responses":{"200":{"description":"Recent reports retrieved successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SuccessReportList"}}}},"401":{"description":"Not authenticated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsHttp401"}}}},"500":{"description":"Server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsHttp500"}}}}}}},"/reports/type/{type}":{"get":{"summary":"Get reports by type","tags":["Reports"],"security":[{"bearerAuth":[]},{"ApiKeyAuth":[]},{"AppKeyAuth":[]}],"parameters":[{"in":"path","name":"type","required":true,"schema":{"type":"string"},"description":"Report type"},{"in":"query","name":"page","schema":{"type":"integer","default":1},"description":"Page number"},{"in":"query","name":"limit","schema":{"type":"integer","default":20},"description":"Items per page"}],"responses":{"200":{"description":"Reports for the given type","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PaginatedReportsResponse"}}}},"401":{"description":"Not authenticated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsHttp401"}}}},"500":{"description":"Server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsHttp500"}}}}}}},"/reports/statistics":{"get":{"summary":"Get report statistics","description":"Counts reports where the current user email matches sender or receiver.","tags":["Reports"],"security":[{"bearerAuth":[]},{"ApiKeyAuth":[]},{"AppKeyAuth":[]}],"responses":{"200":{"description":"Aggregated statistics (zeros if none)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SuccessStatistics"}}}},"401":{"description":"Not authenticated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsHttp401"}}}},"500":{"description":"Server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsHttp500"}}}}}}},"/reports/mr-users":{"get":{"summary":"Get all MR users","description":"Users with guest/MR role (`ROLES.GUEST_USER`); returns `userName` and `email`.","tags":["Reports"],"security":[{"bearerAuth":[]},{"ApiKeyAuth":[]},{"AppKeyAuth":[]}],"responses":{"200":{"description":"MR users list","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SuccessMrUsers"}}}},"401":{"description":"Not authenticated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsHttp401"}}}},"500":{"description":"Server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsHttp500"}}}}}}},"/reports/company/accessed-mr-users":{"get":{"summary":"Get company accessed MR users","description":"Company user only. Not for admin role with separate company. 403 if the user is not a company user type.","tags":["Reports"],"security":[{"bearerAuth":[]},{"ApiKeyAuth":[]},{"AppKeyAuth":[]}],"responses":{"200":{"description":"MR users linked to the company","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CompanyAccessedMrUsersResponse"}}}},"401":{"description":"Not authenticated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsHttp401"}}}},"403":{"description":"User is not a company user (JWT/API resolved user fails `assigned_company` guest pattern)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsHttp403"}}}},"500":{"description":"Server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsHttp500"}}}}}},"put":{"summary":"Update company accessed MR user","description":"Company user only. Updates continuation or replacement state for an MR user tied to the company.","tags":["Reports"],"security":[{"bearerAuth":[]},{"ApiKeyAuth":[]},{"AppKeyAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["_id","isContinue"],"properties":{"_id":{"type":"string","description":"MR user ID"},"isContinue":{"type":"boolean","description":"Whether to continue with MR user"},"replacedMrUserId":{"type":"string","description":"Replacement MR user ID"},"discontinueDate":{"type":"string","format":"date","description":"Discontinue date"}}}}}},"responses":{"200":{"description":"Update succeeded","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Accessed MR user updated successfully"}}}}}},"400":{"description":"Invalid body or business validation from service","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsControllerError"}}}},"401":{"description":"Not authenticated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsHttp401"}}}},"403":{"description":"Not a company user","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsHttp403"}}}},"500":{"description":"Server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsHttp500"}}}}}}},"/reports/{id}/download":{"get":{"summary":"Download report file","description":"Returns HTTP 302 redirect to the stored file URL when the user email matches sender or receiver.\nOn error, response is JSON (not a redirect) with the status code below.\n","tags":["Reports"],"security":[{"bearerAuth":[]},{"ApiKeyAuth":[]},{"AppKeyAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string"},"description":"Report document id"}],"responses":{"302":{"description":"Found — redirect to `reportDetails.report_link`","headers":{"Location":{"schema":{"type":"string","format":"uri"}}}},"400":{"description":"Invalid id","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsControllerError"}}}},"401":{"description":"Not authenticated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsHttp401"}}}},"403":{"description":"Current user is neither sender nor receiver","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsHttp403"}}}},"404":{"description":"Report not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsHttp404"}}}},"500":{"description":"Server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsHttp500"}}}}}}},"/reports/{id}":{"get":{"summary":"Get a specific report by ID","tags":["Reports"],"security":[{"bearerAuth":[]},{"ApiKeyAuth":[]},{"AppKeyAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string"},"description":"Report ID"}],"responses":{"200":{"description":"Report document","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SuccessReport"}}}},"400":{"description":"Invalid id","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsControllerError"}}}},"401":{"description":"Not authenticated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsHttp401"}}}},"404":{"description":"Report not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsHttp404"}}}},"500":{"description":"Server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsHttp500"}}}}}},"put":{"summary":"Update a report","tags":["Reports"],"security":[{"bearerAuth":[]},{"ApiKeyAuth":[]},{"AppKeyAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string"},"description":"Report ID"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"reportDetails":{"type":"object","description":"Partial or full report metadata"},"sender":{"$ref":"#/components/schemas/Party"},"receiver":{"$ref":"#/components/schemas/Party"}}}}}},"responses":{"200":{"description":"Report updated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SuccessReport"}}}},"400":{"description":"Invalid id or body","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsControllerError"}}}},"401":{"description":"Not authenticated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsHttp401"}}}},"404":{"description":"Report not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsHttp404"}}}},"500":{"description":"Server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsHttp500"}}}}}},"delete":{"summary":"Delete a report","tags":["Reports"],"security":[{"bearerAuth":[]},{"ApiKeyAuth":[]},{"AppKeyAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string"},"description":"Report ID"}],"responses":{"200":{"description":"Report deleted","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SuccessDeleteReport"},"example":{"success":true,"message":"Report deleted successfully"}}}},"400":{"description":"Invalid report id","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsControllerError"}}}},"401":{"description":"Not authenticated","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsHttp401"}}}},"404":{"description":"Report not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsHttp404"}}}},"500":{"description":"Server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReportsHttp500"}}}}}}},"/short-order/orderUpdateStatus":{"post":{"summary":"Update short order status","tags":["Short"],"security":[{"ApiKeyAuth":[]},{"AppKeyAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object"}}}},"responses":{"200":{"description":"Status updated"},"400":{"description":"Bad request"}}}},"/transactions":{"post":{"summary":"Create new transaction(s)","description":"Create one or more new transactions. Supports single transaction, array of transactions, or an object with a transactions array.\n**Important Note on reUpload Behavior:** - When a transaction has been downloaded, it cannot be modified unless the `reUpload` flag is set to `true`. - The `reUpload` flag can be set at the global level (applies to all transactions) or at the individual transaction level. - Transaction-level `reUpload` takes precedence over the global setting. - The system checks the latest log entry for download records, not the first one.\n","tags":["Transactions V2"],"security":[{"ApiKeyAuth":[]},{"AppKeyAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"oneOf":[{"$ref":"#/components/schemas/Transaction"},{"type":"array","items":{"$ref":"#/components/schemas/Transaction"}},{"type":"object","properties":{"transactions":{"type":"array","items":{"$ref":"#/components/schemas/Transaction"}},"reUpload":{"type":"boolean","description":"Global reUpload flag. When set to true, allows re-uploading of transactions that have already been downloaded. If false (default), attempting to re-upload a transaction that has been downloaded will result in an error. This flag can be overridden at the individual transaction level.\n","default":false,"example":true},"mailFileIndex":{"type":"number","description":"Index of mail file (for mail imports)"},"messageId":{"type":"string","description":"Message ID (for mail imports)"}}}]}}}},"responses":{"200":{"description":"Transaction(s) created successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Transactions created successfully"},"data":{"type":"object","properties":{"stats":{"type":"object","properties":{"insertedCount":{"type":"number"},"modifiedCount":{"type":"number"},"totalCount":{"type":"number"}}},"transactions":{"type":"array","items":{"type":"object","properties":{"_id":{"type":"string"},"transactionId":{"type":"string"},"transactionType":{"type":"string"},"action":{"type":"string","enum":["created","updated"]}}}},"transactionId":{"type":"string","description":"ID of the created transaction (for single transaction uploads)"},"transaction":{"$ref":"#/components/schemas/Transaction","description":"Full transaction details (for single transaction uploads)"},"bulkUpload":{"type":"boolean","description":"Whether this was a bulk upload (multiple transactions)"},"transactionCount":{"type":"number","description":"Total number of transactions in the request (for bulk uploads)"},"successCount":{"type":"number","description":"Number of successfully processed transactions (for bulk uploads)"}}}}}}}},"400":{"description":"Invalid input data","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string"}}}}}}}},"get":{"summary":"Get transaction(s) by ID","description":"Retrieve a single transaction by query `id` or multiple transactions by providing an `ids` array in the request body.\n","tags":["Transactions V2"],"security":[{"ApiKeyAuth":[]},{"AppKeyAuth":[]},{"bearerAuth":[]}],"parameters":[{"in":"query","name":"id","schema":{"type":"string"},"description":"Transaction MongoDB ID (for single fetch)"}],"requestBody":{"required":false,"content":{"application/json":{"schema":{"type":"object","properties":{"ids":{"type":"array","description":"Array of transaction IDs for batch fetch (processed in chunks of 50)","items":{"type":"string"}}}}}}},"responses":{"200":{"description":"Successfully retrieved transaction(s)","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"message":{"type":"string"},"data":{"type":"object","properties":{"transactions":{"oneOf":[{"$ref":"#/components/schemas/Transaction"},{"type":"array","items":{"$ref":"#/components/schemas/Transaction"}}]},"failed":{"type":"array","description":"Failed IDs with errors (batch mode only)","items":{"type":"object","properties":{"id":{"type":"string"},"error":{"type":"string"}}}}}}}}}}},"400":{"description":"Invalid request (bad ID format, empty ids, or missing id/ids)"}}}},"/transactions/search":{"get":{"summary":"Search transactions with advanced filtering and pagination","description":"Advanced search endpoint for transactions with comprehensive filtering options.\n\n**Key Features:**\n- Flexible date range filtering (transaction or upload date)\n- Party type filtering (sender/receiver perspective)\n- Download status filtering\n- Trade name search with partial matching\n- Efficient pagination\n- Detailed response with transaction summaries\n\n**Date Range Rules:**\n- Maximum range: 30 days\n- Default range: Last 30 days if not specified (optimized search)\n- Supports both YYYY-MM-DD and YYYY/MM/DD formats\n- For upload dates (dateType='upload'), uses MongoDB timestamps\n\n**Party Type Mapping:**\nWhen searching as receiver, transaction types are automatically mapped:\n- Sales Invoice → Purchase Invoice\n- Purchase Order → Sales Order\n- Sales Challan → Purchase Challan\n- Sales Return → Purchase Return\n(and vice versa)\n","tags":["Transactions V2"],"security":[{"ApiKeyAuth":[]},{"AppKeyAuth":[]},{"bearerAuth":[]}],"parameters":[{"in":"query","name":"transactionType","schema":{"type":"string","enum":["Sales Invoice","Purchase Invoice","Sales Order","Purchase Order","Sales Challan","Purchase Challan","Sales Return","Purchase Return","all"]},"description":"Transaction type to search. When partyType=receiver, mapped to the corresponding receiver type."},{"in":"query","name":"partyType","schema":{"type":"string","enum":["sender","receiver"],"default":"receiver"},"description":"Perspective to search from."},{"in":"query","name":"downloadable","schema":{"type":"boolean","default":true},"description":"true = available to download, false = already downloaded/expired."},{"in":"query","name":"startDate","schema":{"type":"string","format":"date"},"description":"Start date (YYYY-MM-DD or YYYY/MM/DD)."},{"in":"query","name":"endDate","schema":{"type":"string","format":"date"},"description":"End date (YYYY-MM-DD or YYYY/MM/DD)."},{"in":"query","name":"dateType","schema":{"type":"string","enum":["transaction","upload"],"default":"upload"},"description":"Filter by transaction date or upload timestamp."},{"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":75},"description":"Page size (capped at 100)."},{"in":"query","name":"detail","schema":{"type":"boolean","default":true},"description":"Whether to include full transaction details."},{"in":"query","name":"tradeName","schema":{"type":"string"},"description":"Partial match on receiver trade name."},{"in":"query","name":"transactionId","schema":{"type":"string"},"description":"Filter by transaction ID."},{"in":"query","name":"transactionDate","schema":{"type":"string","format":"date"},"description":"Filter by specific transaction date."},{"in":"query","name":"upload_by","schema":{"type":"string"},"description":"Filter by uploader company ID (sender)."},{"in":"query","name":"fastSearch","schema":{"type":"string","enum":[true,false,"auto"],"default":true},"description":"Deprecated. Compact search is used by default."},{"in":"query","name":"dateRangeHint","schema":{"type":"string"},"description":"JSON string hint to maintain consistent pagination windows."}],"responses":{"200":{"description":"Successfully retrieved transactions","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Transactions found successfully"},"data":{"type":"object","properties":{"transactions":{"type":"array","items":{"type":"object","properties":{"_id":{"type":"string","description":"MongoDB ID of the transaction"},"TransactionDetails":{"type":"object","properties":{"transactionDate":{"type":"string","description":"Date of transaction"},"transactionType":{"type":"string","description":"Type of transaction"},"transactionID":{"type":"string","description":"Transaction identifier"}}},"senderDetails":{"$ref":"#/components/schemas/PartyDetails"},"receiverDetails":{"$ref":"#/components/schemas/PartyDetails"},"valueDetails":{"type":"object","properties":{"totalAmount":{"type":"number","description":"Total transaction amount"}}},"downloadable":{"type":"boolean","description":"Whether transaction can be downloaded"},"createdAt":{"type":"string","format":"date-time","description":"When transaction was created"},"log":{"type":"array","items":{"type":"object","properties":{"upload_at":{"type":"string","format":"date-time"},"download_log":{"type":"array","items":{"type":"object"}},"cancel_log":{"type":"object"}}}}}}},"pagination":{"type":"object","properties":{"page":{"type":"integer","description":"Current page number"},"limit":{"type":"integer","description":"Items per page"},"total":{"type":"integer","description":"Total number of matching transactions"},"pages":{"type":"integer","description":"Total number of pages"}}},"dateRange":{"type":"object","properties":{"start":{"type":"string","description":"Start date used in query"},"end":{"type":"string","description":"End date used in query"},"isDefaultRange":{"type":"boolean","description":"Whether default date range was used"}}}}}}}}}},"400":{"description":"Invalid request parameters","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string"},"error":{"type":"object","properties":{"code":{"type":"string"},"details":{"type":"string"}}}}}}}},"401":{"description":"Authentication failed"},"403":{"description":"Permission denied"},"429":{"description":"Too many requests - rate limit exceeded"}},"x-codeSamples":[{"lang":"curl","source":"curl -G \"https://api.swilunify.com/transactions/search\" \\\n  -H \"x-api-key: YOUR_API_KEY\" \\\n  -H \"x-app-key: YOUR_APP_KEY\" \\\n  --data-urlencode \"transactionType=Purchase Invoice\" \\\n  --data-urlencode \"partyType=receiver\" \\\n  --data-urlencode \"downloadable=true\" \\\n  --data-urlencode \"startDate=2024-03-01\" \\\n  --data-urlencode \"endDate=2024-03-15\" \\\n  --data-urlencode \"dateType=transaction\" \\\n  --data-urlencode \"page=1\" \\\n  --data-urlencode \"limit=20\"\n"},{"lang":"javascript","source":"const params = new URLSearchParams({\n  transactionType: 'Purchase Invoice',\n  partyType: 'receiver',\n  downloadable: 'true',\n  startDate: '2024-03-01',\n  endDate: '2024-03-15',\n  dateType: 'transaction',\n  page: '1',\n  limit: '20'\n});\nconst response = await fetch(`https://api.swilunify.com/transactions/search?${params.toString()}`, {\n  headers: {\n    'x-api-key': 'YOUR_API_KEY',\n    'x-app-key': 'YOUR_APP_KEY'\n  }\n});\n"}]}},"/transactions/cancel":{"post":{"summary":"Cancel or undo cancellation of a transaction","description":"Cancel a transaction or undo a previous cancellation. Only transactions that haven't been downloaded can be cancelled.\n\n**Key Features:**\n- Cancel undownloaded transactions\n- Undo previous cancellations\n- Automatic notification to affected parties\n- Maintains cancellation history in transaction logs\n\n**Cancellation Rules:**\n1. Only the original uploader can cancel a transaction\n2. Transactions that have been downloaded cannot be cancelled\n3. Cancelled transactions become non-downloadable\n4. Cancellation can be undone if needed\n\n**Important Notes:**\n- Cancellation requires exact match of transaction ID, type, and date\n- Once cancelled, the transaction remains in the system but is marked as non-downloadable\n- Cancellation logs are maintained for audit purposes\n- Both parties (sender and receiver) are notified of cancellation\n","tags":["Transactions V2"],"security":[{"ApiKeyAuth":[]},{"AppKeyAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["transactionDetails"],"properties":{"transactionDetails":{"type":"object","required":["transactionId","transactionType","transactionDate"],"properties":{"transactionId":{"type":"string","description":"Unique identifier of the transaction","example":"INV-001"},"transactionType":{"type":"string","enum":["Sales Invoice","Purchase Invoice","Sales Order","Purchase Order","Sales Challan","Purchase Challan","Sales Return","Purchase Return"],"description":"Type of transaction","example":"Sales Invoice"},"transactionDate":{"type":"string","format":"date","description":"Date in YYYY-MM-DD or YYYY/MM/DD format","example":"2024/03/15"}}},"undoCancel":{"type":"boolean","description":"Set to true to undo a previous cancellation","default":false,"example":false},"cancelReason":{"type":"string","description":"Optional reason for cancellation","example":"Incorrect transaction details"}}}}}},"responses":{"200":{"description":"Transaction cancelled or uncancelled successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Transaction cancelled successfully"},"data":{"type":"object","properties":{"_id":{"type":"string","description":"MongoDB ID of the transaction"},"TransactionDetails":{"type":"object","properties":{"transactionId":{"type":"string"},"transactionType":{"type":"string"},"transactionDate":{"type":"string"}}},"downloadable":{"type":"boolean","description":"Always false after cancellation, true after undo"},"log":{"type":"array","items":{"type":"object","properties":{"upload_at":{"type":"string","format":"date-time"},"cancel_log":{"type":"object","properties":{"cancel_by":{"type":"string","description":"Company/user ID who cancelled"},"cancel_from":{"type":"string","description":"Application source"},"cancel_at":{"type":"string","format":"date-time"},"isCanceled":{"type":"boolean"},"reason":{"type":"string"}}}}}}}}}}}}},"400":{"description":"Invalid request or transaction already downloaded","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Cannot cancel transaction as it has already been downloaded"},"error":{"type":"object","properties":{"code":{"type":"string","enum":["ALREADY_DOWNLOADED","INVALID_TRANSACTION","TRANSACTION_NOT_FOUND","UNAUTHORIZED_CANCEL"]},"details":{"type":"string"}}}}}}}},"401":{"description":"Authentication failed"},"403":{"description":"Not authorized to cancel this transaction","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Only the original uploader can cancel this transaction"}}}}}},"404":{"description":"Transaction not found","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Transaction not found"}}}}}}},"x-codeSamples":[{"lang":"curl","source":"curl -X POST \"https://api.swilunify.com/transactions/cancel\" \\\n  -H \"x-api-key: YOUR_API_KEY\" \\\n  -H \"x-app-key: YOUR_APP_KEY\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"transactionDetails\": {\n      \"transactionId\": \"INV-001\",\n      \"transactionType\": \"Sales Invoice\",\n      \"transactionDate\": \"2024/03/15\"\n    },\n    \"cancelReason\": \"Incorrect transaction details\"\n  }'\n"},{"lang":"javascript","source":"const response = await fetch('https://api.swilunify.com/transactions/cancel', {\n  method: 'POST',\n  headers: {\n    'x-api-key': 'YOUR_API_KEY',\n    'x-app-key': 'YOUR_APP_KEY',\n    'Content-Type': 'application/json'\n  },\n  body: JSON.stringify({\n    transactionDetails: {\n      transactionId: 'INV-001',\n      transactionType: 'Sales Invoice',\n      transactionDate: '2024/03/15'\n    },\n    cancelReason: 'Incorrect transaction details'\n  })\n});\n\n// To undo a cancellation\nconst undoResponse = await fetch('https://api.swilunify.com/transactions/cancel', {\n  method: 'POST',\n  headers: {\n    'x-api-key': 'YOUR_API_KEY',\n    'x-app-key': 'YOUR_APP_KEY',\n    'Content-Type': 'application/json'\n  },\n  body: JSON.stringify({\n    transactionDetails: {\n      transactionId: 'INV-001',\n      transactionType: 'Sales Invoice',\n      transactionDate: '2024/03/15'\n    },\n    undoCancel: true\n  })\n});\n"}]}},"/transactions/download":{"post":{"summary":"Update transaction download status","description":"Mark a transaction as downloaded or cancel its download status.\n\n**Key Features:**\n- Supports both single and batch downloads\n- Maintains download history in transaction logs\n- Handles legacy download status migration\n\n**Download Status Rules:**\n1. Downloaded transactions cannot be re-uploaded without reUpload flag\n2. Cancelled transactions remain non-downloadable\n3. Download history is preserved in the log structure\n","tags":["Transactions V2"],"security":[{"ApiKeyAuth":[]},{"AppKeyAuth":[]},{"bearerAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string","description":"Transaction MongoDB ID"},"cancelDownload":{"type":"boolean","default":false,"description":"Whether to cancel the download status"}}}}}},"responses":{"200":{"description":"Download status updated successfully"},"400":{"description":"Invalid input or transaction already downloaded"},"404":{"description":"Transaction not found"}}}},"/transactions/expiry":{"post":{"summary":"Update transaction expiry status","description":"Mark a transaction as expired or active.\n\n**Expiry Rules:**\n1. Expired transactions are automatically marked as non-downloadable\n2. Un-expiring a transaction makes it downloadable again\n3. Expiry reason is required when marking as expired\n\n**Expiry Types:**\n- EXPIRED: System-determined expiry\n- USER_REQUEST: Manual expiry by user\n","tags":["Transactions V2"],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["isExpired"],"properties":{"isExpired":{"type":"boolean","description":"Whether to mark as expired"},"expiryReason":{"type":"string","enum":["EXPIRED","USER_REQUEST"],"default":"USER_REQUEST","description":"Reason for expiry"}}}}}},"responses":{"200":{"description":"Expiry status updated successfully"},"400":{"description":"Invalid input"},"404":{"description":"Transaction not found"}}}},"/transactions/bulk-download":{"post":{"summary":"Bulk update download status for multiple transactions","description":"Process download status updates for multiple transactions in an efficient batched manner.\n\n**Key Features:**\n- Automatic batch processing (50 transactions per batch)\n- Parallel processing within batches\n- Detailed success/failure tracking\n- Maintains audit logs for each transaction\n\n**Processing Rules:**\n1. Transactions are processed in batches of 50 to optimize performance\n2. Each transaction's download status is updated independently\n3. Failed updates don't affect other transactions in the batch\n4. Download history is maintained in each transaction's log\n\n**Common Failure Scenarios:**\n- Transaction already downloaded\n- Transaction marked as expired\n- Invalid transaction ID\n- Insufficient permissions\n","tags":["Transactions V2"],"security":[{"ApiKeyAuth":[]},{"AppKeyAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["transactionIds"],"properties":{"transactionIds":{"type":"array","items":{"type":"string","description":"MongoDB ObjectId of the transaction"},"maxItems":1000,"description":"Array of transaction IDs to mark as downloaded"},"cancelDownload":{"type":"boolean","default":false,"description":"Whether to cancel download status for all transactions"}}}}}},"responses":{"200":{"description":"Bulk update completed with detailed results","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"message":{"type":"string","example":"Successfully updated 45 of 50 transactions"},"data":{"type":"object","properties":{"total":{"type":"integer","description":"Total number of transactions processed"},"successful":{"type":"array","items":{"type":"string"},"description":"IDs of successfully updated transactions"},"failed":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string"},"error":{"type":"string"},"code":{"type":"string","enum":["ALREADY_DOWNLOADED","EXPIRED","INVALID_ID","NOT_FOUND","PERMISSION_DENIED"]}}}}}}}}}}},"400":{"description":"Invalid request parameters","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"},"example":{"success":false,"message":"Invalid request parameters","code":"INVALID_INPUT","data":{"reason":"transactionIds array is required"}}}}},"429":{"description":"Too many requests - rate limit exceeded"}}}},"/transactions/export":{"get":{"summary":"Export a transaction as CSV in various formats","description":"Export a single transaction as CSV file with support for multiple formats.\n\n**Supported Formats:**\n- `generic`: Clean, standardized format with common headers\n- `structured`: H/T/F records format (Header/Transaction/Footer) - matches legacy generateCsv.js\n- `flat`: Header + line items format - matches legacy withHeaderCsv.js\n- `zoho`: Optimized for Zoho Books import\n- `tally`: Optimized for Tally import\n- `marg`: Generic format for Marg software\n\n**File Download:**\n- Returns CSV content with proper Content-Type headers\n- Filename format: `{TransactionType}-{TransactionID}-{format}.csv`\n- Example: `Sales-Invoice-INV-001-zoho.csv`\n","tags":["Transactions V2"],"security":[{"ApiKeyAuth":[]},{"AppKeyAuth":[]},{"bearerAuth":[]}],"parameters":[{"in":"query","name":"id","schema":{"type":"string","pattern":"^[0-9a-fA-F]{24}$"},"required":true,"description":"MongoDB ObjectId of the transaction to export","example":"65f1234567890abcdef12345"},{"in":"query","name":"format","schema":{"type":"string","enum":["generic","zoho","tally","marg","structured","flat"],"default":"generic"},"description":"Target CSV format:\n- `generic`: Standard format with clean headers\n- `structured`: H/T/F records (Header/Transaction/Footer) - legacy format\n- `flat`: Header + line items - legacy format\n- `zoho`: Optimized for Zoho Books\n- `tally`: Optimized for Tally\n- `marg`: Generic format for Marg software\n","example":"zoho"}],"responses":{"200":{"description":"CSV file successfully generated and returned","content":{"text/csv":{"schema":{"type":"string","format":"binary"},"example":"Customer Name,Invoice Number,Invoice Date,Company Name,Item Code,Barcode,Item Name,Packing,Batch No,Expiry,Rate,MRP,Quantity,Free Quantity,PTR Disc,PTS Disc,Lot Disc,Taxable Amount,IGST %,IGST Amount,CGST %,CGST Amount,SGST %,SGST Amount,Cess %,Cess Amount,HSN,GSTIN\nXYZ Pharma,INV-001,15/03/2024,MediCorp,SKU001,123456789,Paracetamol 500mg,500mg,BATCH001,2025/12/31,10.5,15,100,10,5,2,1,1000,18,180,9,90,9,90,0,0,30049099,29BBBD5678C2ZB\n"}},"headers":{"Content-Disposition":{"description":"Attachment filename","schema":{"type":"string","example":"Sales-Invoice-INV-001-zoho.csv"}},"Content-Type":{"description":"MIME type for CSV","schema":{"type":"string","example":"text/csv; charset=utf-8"}}}},"400":{"description":"Invalid request parameters","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Transaction ID is required"},"code":{"type":"string","enum":["REQUIRED_FIELD_MISSING","INVALID_INPUT"]},"data":{"type":"object","properties":{"field":{"type":"string","example":"id"},"transactionId":{"type":"string","example":"invalid-id"}}}}}}}},"401":{"description":"Authentication required","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Authentication required: provide Authorization: Bearer <token> or x-api-key and x-app-key headers."}}}}}},"403":{"description":"Access denied - transaction not accessible by company","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Transaction not accessible by your company"}}}}}},"404":{"description":"Transaction not found","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Transaction not found"},"code":{"type":"string","example":"NOT_FOUND"}}}}}},"500":{"description":"Internal server error during CSV generation","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"message":{"type":"string","example":"Error generating CSV"},"code":{"type":"string","example":"INTERNAL_ERROR"},"data":{"type":"object","properties":{"id":{"type":"string"},"format":{"type":"string"},"error":{"type":"string"}}}}}}}}},"x-codeSamples":[{"lang":"curl","source":"curl -G \"https://api.swilunify.com/transactions/export\" \\\n  -H \"x-api-key: YOUR_API_KEY\" \\\n  -H \"x-app-key: YOUR_APP_KEY\" \\\n  --data-urlencode \"id=65f1234567890abcdef12345\" \\\n  --data-urlencode \"format=zoho\" \\\n  --output \"transaction.csv\"\n"},{"lang":"javascript","source":"const response = await fetch('https://api.swilunify.com/transactions/export?id=65f1234567890abcdef12345&format=zoho', {\n  headers: {\n    'x-api-key': 'YOUR_API_KEY',\n    'x-app-key': 'YOUR_APP_KEY'\n  }\n});\n\nif (response.ok) {\n  const blob = await response.blob();\n  const url = window.URL.createObjectURL(blob);\n  const a = document.createElement('a');\n  a.href = url;\n  a.download = 'transaction.csv';\n  a.click();\n}\n"}]}},"/users/profile":{"get":{"summary":"Get user profile","description":"Retrieve the authenticated user's profile including company details.\n\n**Authentication Required**: Yes (JWT Bearer Token)\n\n**Returns**: Complete user profile with associated company information\n\n**Multi-Tenant**: Automatically filters by authenticated user's ID\n\n**Use Cases**:\n- Display user profile in UI\n- Verify user permissions and role\n- Show company association\n- Profile settings page\n\n**Consumption Profile**: Platform (app.swilunify.com)\n","tags":["User Management"],"security":[{"BearerAuth":[]},{"AppKeyAuth":[]}],"responses":{"200":{"description":"User profile retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Profile retrieved successfully"},"data":{"$ref":"#/components/schemas/UserProfile"}}},"example":{"success":true,"message":"Profile retrieved successfully","data":{"_id":"507f1f77bcf86cd799439011","userName":"John Doe","email":"john@example.com","phone_no":"+919876543210","role":"ADMIN","isActive":true,"accountStatus":"APPROVED","createdAt":"2024-01-10T08:00:00Z","companyDetail":{"_id":"507f1f77bcf86cd799439012","company_name":"ABC Electronics Pvt Ltd","gst_no":"27AABCU9603R1ZM","pan":"AABCU9603R"}}}}}},"401":{"description":"Unauthorized - Invalid or missing token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"404":{"description":"User not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/users/sub-users":{"get":{"summary":"Get sub-users for a company","description":"Retrieve list of all sub-users associated with the authenticated user's company.\nSub-users are additional users created under a company account.\n\n**Authentication Required**: Yes (JWT Bearer Token)\n\n**Returns**: List of sub-users with their profiles and company association\n\n**Multi-Tenant**: Automatically filters by authenticated user's company ID\n\n**Business Rules**:\n- Only returns users from the same company\n- Includes company profile image\n- Shows all sub-users regardless of status\n\n**Use Cases**:\n- Display team members list\n- Manage company users\n- User administration panel\n- Access control management\n\n**Consumption Profile**: Platform (app.swilunify.com)\n","tags":["User Management"],"security":[{"BearerAuth":[]},{"AppKeyAuth":[]}],"responses":{"200":{"description":"Sub-users retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Sub-users retrieved successfully"},"data":{"type":"array","items":{"$ref":"#/components/schemas/SubUser"}}}}}}},"401":{"description":"Unauthorized - Invalid or missing token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/users/sub-users/{id}":{"patch":{"summary":"Update sub-user status","description":"Update the active status of a sub-user (enable/disable user access).\n\n**Authentication Required**: Yes (JWT Bearer Token)\n\n**Authorization**: Company admin can manage their sub-users\n\n**Business Rules**:\n- Only company admins can update sub-user status\n- Cannot update own status\n- Status change is immediate\n- Disabled users cannot login\n\n**Use Cases**:\n- Enable/disable user access\n- Temporary user suspension\n- User offboarding\n- Access control management\n\n**Consumption Profile**: Platform (app.swilunify.com)\n","tags":["User Management"],"security":[{"BearerAuth":[]},{"AppKeyAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","example":"507f1f77bcf86cd799439011"},"description":"Sub-user ID (MongoDB ObjectId)"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["isActive"],"properties":{"isActive":{"type":"boolean","description":"User active status (true = enabled, false = disabled)","example":true}}},"examples":{"enableUser":{"summary":"Enable user access","value":{"isActive":true}},"disableUser":{"summary":"Disable user access","value":{"isActive":false}}}}}},"responses":{"200":{"description":"Sub-user updated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Sub-user updated successfully"},"data":{"$ref":"#/components/schemas/SubUser"}}}}}},"400":{"description":"Invalid input data or missing required fields","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"examples":{"missingStatus":{"summary":"Missing isActive field","value":{"success":false,"statusCode":400,"message":"Please provide an action"}},"missingId":{"summary":"Missing user ID","value":{"success":false,"statusCode":400,"message":"User ID not found"}}}}}},"401":{"description":"Unauthorized - Invalid or missing token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"404":{"description":"User not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/users/send-invitation":{"post":{"summary":"Send invitation email to sub-user","description":"Send an invitation email to a new sub-user with a signup link.\nThe invitation contains an encrypted token for secure signup.\n\n**Authentication Required**: Yes (JWT Bearer Token)\n\n**Authorization**: Company admin can send invitations\n\n**Business Rules**:\n- Token must be encrypted before sending\n- Email must be valid format\n- Company must exist\n- Invitation link includes company context\n- Email template: CREATE_SUB_USER_KEY\n\n**Email Contents**:\n- Company name\n- Signup link with encrypted token\n- Username (email)\n- Instructions for account creation\n\n**Use Cases**:\n- Invite new team members\n- Onboard sub-users\n- Grant company access\n- User provisioning\n\n**Consumption Profile**: Platform (app.swilunify.com)\n","tags":["User Management"],"security":[{"BearerAuth":[]},{"AppKeyAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["token","email"],"properties":{"token":{"type":"string","description":"Encrypted invitation token containing user and company data","example":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."},"email":{"type":"string","format":"email","description":"Recipient email address","example":"newuser@example.com"}}},"example":{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...","email":"newuser@example.com"}}}},"responses":{"200":{"description":"Invitation email sent successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Email sent to: newuser@example.com"}}}}}},"400":{"description":"Invalid input data or missing required fields","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"example":{"success":false,"statusCode":400,"message":"Please provide necessary data"}}}},"401":{"description":"Unauthorized - Invalid or missing token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"404":{"description":"Company not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"example":{"success":false,"statusCode":404,"message":"Company not found"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/users/mr-users":{"get":{"summary":"Get MR users list","description":"Retrieve list of all Medical Representative (MR) users in the system.\nMR users are special user type for pharmaceutical companies.\n\n**Authentication Required**: Yes (JWT Bearer Token)\n\n**Returns**: List of all MR users with their profiles\n\n**User Type**: Guest User (GUEST_USER role)\n\n**Business Rules**:\n- Returns all users with role 'Guest User'\n- MR users have special email for report uploads\n- Independent from company admin users\n\n**Use Cases**:\n- View all MR users\n- MR user administration\n- Sales team management\n- Pharmaceutical company operations\n\n**Consumption Profile**: Platform (app.swilunify.com)\n","tags":["User Management"],"security":[{"BearerAuth":[]},{"AppKeyAuth":[]}],"responses":{"200":{"description":"MR users retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"MR users retrieved successfully"},"data":{"type":"array","items":{"type":"object","properties":{"_id":{"type":"string"},"userName":{"type":"string"},"email":{"type":"string"},"phone_no":{"type":"string"},"role":{"type":"string","example":"Guest User"},"isActive":{"type":"boolean"},"mrReportEmail":{"type":"string","example":"507f1f77bcf86cd799439011@upload.swilunify.com"}}}}}}}}},"401":{"description":"Unauthorized - Invalid or missing token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/users/mr-users/{id}":{"get":{"summary":"Get MR user detail","description":"Retrieve detailed information about a specific Medical Representative (MR) user.\n\n**Authentication Required**: Yes (JWT Bearer Token)\n\n**Returns**: Complete MR user profile with all details\n\n**Use Cases**:\n- View MR user profile\n- Verify MR user details\n- MR user management\n- Sales team administration\n\n**Consumption Profile**: Platform (app.swilunify.com)\n","tags":["User Management"],"security":[{"BearerAuth":[]},{"AppKeyAuth":[]}],"parameters":[{"in":"path","name":"id","required":true,"schema":{"type":"string","example":"507f1f77bcf86cd799439011"},"description":"MR user ID (MongoDB ObjectId)"}],"responses":{"200":{"description":"MR user detail retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"MR user detail retrieved successfully"},"data":{"type":"object","properties":{"_id":{"type":"string"},"userName":{"type":"string"},"email":{"type":"string"},"phone_no":{"type":"string"},"role":{"type":"string","example":"Guest User"},"isActive":{"type":"boolean"},"mrReportEmail":{"type":"string"},"createdAt":{"type":"string","format":"date-time"}}}}}}}},"400":{"description":"Invalid or missing user ID","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"example":{"success":false,"statusCode":400,"message":"Please provide an ID"}}}},"401":{"description":"Unauthorized - Invalid or missing token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"404":{"description":"MR user not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"example":{"success":false,"statusCode":404,"message":"MR user not found"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/users/create-draft":{"post":{"summary":"Create a drafted user","description":"Create a new user in draft status (not yet fully registered).\nDraft users can be completed later through the signup process.\n\n**Authentication Required**: Yes (JWT Bearer Token)\n\n**Business Rules**:\n- User created in draft state\n- Can be completed via invitation link\n- Minimal validation for draft creation\n- Used for pre-provisioning users\n\n**Use Cases**:\n- Pre-create user accounts\n- Bulk user provisioning\n- User invitation workflow\n- Team onboarding preparation\n\n**Consumption Profile**: Platform (app.swilunify.com)\n","tags":["User Management"],"security":[{"BearerAuth":[]},{"AppKeyAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"userName":{"type":"string","description":"User's full name","example":"Jane Smith"},"email":{"type":"string","format":"email","description":"User's email address","example":"jane@example.com"},"phone_no":{"type":"string","description":"User's phone number","example":"+919876543210"},"role":{"type":"string","description":"User role","example":"USER"}}},"example":{"userName":"Jane Smith","email":"jane@example.com","phone_no":"+919876543210","role":"USER"}}}},"responses":{"200":{"description":"Drafted user created successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"user":{"type":"object","properties":{"_id":{"type":"string"},"userName":{"type":"string"},"email":{"type":"string"},"phone_no":{"type":"string"},"role":{"type":"string"}}}}}}}},"400":{"description":"Invalid input data","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"401":{"description":"Unauthorized - Invalid or missing token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/users/search":{"get":{"summary":"Search users with filters and pagination","description":"Advanced user search with multiple filters and pagination support.\nSupports searching by name, email, status, role, and company.\n\n**Authentication Required**: Yes (JWT Bearer Token)\n\n**Returns**: Paginated list of users matching search criteria\n\n**Filter Options**:\n- **status**: Filter by active/inactive status\n- **company**: Filter by company ID\n- **role**: Filter by user role\n- **accountStatus**: Filter by account status\n- **search**: Text search in name or email\n\n**Pagination**: Default 20 users per page\n\n**Sorting**: Configurable by field and order\n\n**Use Cases**:\n- User directory search\n- Admin user management\n- Team member lookup\n- User analytics\n\n**Consumption Profile**: Platform (app.swilunify.com)\n","tags":["User Management"],"security":[{"BearerAuth":[]},{"AppKeyAuth":[]}],"parameters":[{"in":"query","name":"status","schema":{"type":"string","enum":["active","inactive"]},"description":"Filter by user active status","example":"active"},{"in":"query","name":"company","schema":{"type":"string"},"description":"Filter by company ID (MongoDB ObjectId)","example":"507f1f77bcf86cd799439012"},{"in":"query","name":"role","schema":{"type":"string","enum":["ADMIN","USER","GUEST_USER"]},"description":"Filter by user role","example":"ADMIN"},{"in":"query","name":"accountStatus","schema":{"type":"string","enum":["PENDING","APPROVED","REJECTED","CLAIMED"]},"description":"Filter by account status","example":"APPROVED"},{"in":"query","name":"search","schema":{"type":"string"},"description":"Search text (searches in userName and email)","example":"john"},{"in":"query","name":"page","schema":{"type":"integer","default":1,"minimum":1},"description":"Page number for pagination","example":1},{"in":"query","name":"limit","schema":{"type":"integer","default":20,"minimum":1,"maximum":100},"description":"Number of items per page","example":20},{"in":"query","name":"sortBy","schema":{"type":"string","default":"createdAt"},"description":"Field to sort by","example":"createdAt"},{"in":"query","name":"sortOrder","schema":{"type":"integer","enum":[1,-1],"default":-1},"description":"Sort order (1 = ascending, -1 = descending)","example":-1}],"responses":{"200":{"description":"Users retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Users retrieved successfully"},"data":{"type":"object","properties":{"users":{"type":"array","items":{"type":"object","properties":{"_id":{"type":"string"},"userName":{"type":"string"},"email":{"type":"string"},"phone_no":{"type":"string"},"isActive":{"type":"boolean"},"accountStatus":{"type":"string"},"role":{"type":"string"},"createdAt":{"type":"string","format":"date-time"},"companyDetail":{"type":"object","properties":{"company_name":{"type":"string"},"gst_no":{"type":"string"},"pan":{"type":"string"}}}}}},"pagination":{"type":"object","properties":{"page":{"type":"integer","example":1},"limit":{"type":"integer","example":20},"total":{"type":"integer","example":150},"pages":{"type":"integer","example":8}}}}}}}}}},"401":{"description":"Unauthorized - Invalid or missing token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}},"/users/statistics":{"get":{"summary":"Get user statistics","description":"Retrieve comprehensive user statistics and analytics.\nProvides insights into user distribution, status, and roles.\n\n**Authentication Required**: Yes (JWT Bearer Token)\n\n**Returns**: Aggregated user statistics\n\n**Statistics Included**:\n- **totalUsers**: Total registered users\n- **activeUsers**: Users with isActive = true\n- **adminUsers**: Users with ADMIN role\n- **guestUsers**: Users with Guest User role (MR users)\n- **approvedUsers**: Users with APPROVED account status\n- **pendingUsers**: Users with PENDING account status\n\n**Use Cases**:\n- Dashboard analytics\n- User metrics reporting\n- Platform health monitoring\n- Business intelligence\n\n**Consumption Profile**: Platform (app.swilunify.com)\n","tags":["User Management"],"security":[{"BearerAuth":[]},{"AppKeyAuth":[]}],"responses":{"200":{"description":"User statistics retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"User statistics retrieved successfully"},"data":{"$ref":"#/components/schemas/UserStatistics"}}},"example":{"success":true,"message":"User statistics retrieved successfully","data":{"totalUsers":1500,"activeUsers":1400,"adminUsers":1200,"guestUsers":300,"approvedUsers":1300,"pendingUsers":200}}}}},"401":{"description":"Unauthorized - Invalid or missing token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}}}}}},"tags":[{"name":"Admin Management","description":"Administrative endpoints for SwilUnify platform management.\n**Access**: Super Admin only\n\nSupports comprehensive admin operations including:\n- **User Management**: View and manage registered users\n- **Account Approval**: Approve/reject user registrations\n- **Ownership Management**: Handle company ownership claims\n- **Super Admin Management**: Create and manage super admin users\n- **Statistics**: Platform analytics and insights\n- **MR User Management**: Block/unblock medical representative users\n"},{"name":"API Key Management","description":"API key generation, management, and verification endpoints.\n**Access**: Authenticated company admin users\n\nAPI keys enable secure server-to-server communication for ERP integrations.\n\n**Key Features**:\n- **Generation**: Create new API keys for company\n- **Regeneration**: Invalidate old key and generate new one\n- **Verification**: Validate API key authenticity\n- **Revocation**: Permanently disable API key\n- **Details**: View masked API key information\n"},{"name":"Authentication","description":"Authentication and authorization endpoints for SwilUnify B2B platform.\nSupports multiple authentication methods:\n- **Basic Auth**: Email/password login with SSO verification\n- **API Key Auth**: Server-to-server authentication for ERP integrations\n- **JWT Bearer Token**: Session-based authentication for web/mobile apps\n- **Multi-Branch**: Support for parent-child company relationships\n- **Ownership Claims**: Handle company ownership verification\n"},{"name":"Company Management","description":"Company profile and management endpoints for SwilUnify B2B platform.\nSupports comprehensive company operations including:\n- **Profile Management**: View and update company details\n- **Multi-Branch Support**: Manage parent-child company relationships\n- **Company Search**: Find companies by name, GST, or PAN\n- **Branch Management**: Manage branch status and permissions\n- **Statistics**: Get company analytics and insights\n- **Advanced Search**: Filter companies with multiple criteria\n"},{"name":"CSV Definitions V2","description":"Manage CSV mapping definitions (HTF and flat) per company"},{"name":"Dashboard","description":"Dashboard analytics and transaction statistics endpoints"},{"name":"Mail","description":"Mailbox endpoints for users/companies"},{"name":"Masters","description":"Master data endpoints (country/state/pincode/currency/unit)"},{"name":"Reports","description":"Report upload, listing, and MR user endpoints. Use Bearer JWT or x-api-key plus x-app-key (see per-operation security)."},{"name":"Short","description":"Short order endpoints"},{"name":"Transactions V2","description":"Transaction management APIs"},{"name":"User Management","description":"User management and profile endpoints for SwilUnify platform.\n**Access**: Authenticated users\n\nSupports comprehensive user operations including:\n- **Profile Management**: View and update user profiles\n- **Sub-User Management**: Manage company sub-users and invitations\n- **MR User Management**: Medical representative user operations\n- **User Search**: Advanced search with filters and pagination\n- **Statistics**: User analytics and metrics\n"}]}