API Changelog (v1)
This document summarizes all recent changes, additions, and updates to the Placio API v1.
Recent Updates
Labs Module - AI Interpretation Enhancements
Updated: Enhanced AI interpretation endpoints with language selection and cost estimation.
New Endpoints
- GET
/api/v1/workspace/:workspaceId/labs/tests/:testId/items/:itemId/interpret/estimate- Estimate cost for AI interpretation before generating
Updated Endpoints
- POST
/api/v1/workspace/:workspaceId/labs/tests/:testId/items/:itemId/interpret- Now acceptslanguageparameter in request bodylanguage(optional):"ar"for Arabic or"en"for English (default:"en")
Changes
- Language Selection: Added support for choosing output language (Arabic/English) for interpretations
- Cost Estimation: New endpoint to estimate interpretation cost before generation
- Improved Accuracy: Cost estimation improved to use realistic token counts (400 tokens instead of 1000)
- Response Format: Interpretation text direction automatically adjusts based on selected language
Request Example
{
"language": "ar"
}
Labs Module
Added: Comprehensive laboratory tests and analyses management API endpoints with reference ranges, result evaluation, and AI-powered interpretation.
New Endpoints
Test Units Management:
- GET
/api/v1/workspace/:workspaceId/labs/units- List all test units - POST
/api/v1/workspace/:workspaceId/labs/units- Create a new test unit - PATCH
/api/v1/workspace/:workspaceId/labs/units/:unitId- Update a test unit - POST
/api/v1/workspace/:workspaceId/labs/units/:unitId/deactivate- Deactivate a test unit
Analyses Management:
- GET
/api/v1/workspace/:workspaceId/labs/analyses- List all analyses - POST
/api/v1/workspace/:workspaceId/labs/analyses- Create a new analysis - GET
/api/v1/workspace/:workspaceId/labs/analyses/:analysisId- Get a single analysis - PATCH
/api/v1/workspace/:workspaceId/labs/analyses/:analysisId- Update an analysis - POST
/api/v1/workspace/:workspaceId/labs/analyses/:analysisId/deactivate- Deactivate an analysis
Analysis Ranges:
- POST
/api/v1/workspace/:workspaceId/labs/analyses/:analysisId/ranges- Add a reference range to an analysis - PATCH
/api/v1/workspace/:workspaceId/labs/analyses/:analysisId/ranges/:rangeId- Update a reference range - DELETE
/api/v1/workspace/:workspaceId/labs/analyses/:analysisId/ranges/:rangeId- Delete a reference range
Tests Management:
- GET
/api/v1/workspace/:workspaceId/labs/tests- List all tests with optional filtering - POST
/api/v1/workspace/:workspaceId/labs/tests- Create a new test - GET
/api/v1/workspace/:workspaceId/labs/tests/:testId- Get a single test - PATCH
/api/v1/workspace/:workspaceId/labs/tests/:testId- Update a test - POST
/api/v1/workspace/:workspaceId/labs/tests/:testId/complete- Mark a test as completed - POST
/api/v1/workspace/:workspaceId/labs/tests/:testId/items- Add an analysis to a test - DELETE
/api/v1/workspace/:workspaceId/labs/tests/:testId/items/:itemId- Remove an analysis from a test - PATCH
/api/v1/workspace/:workspaceId/labs/tests/:testId/items/:itemId/result- Save result for a test item - POST
/api/v1/workspace/:workspaceId/labs/tests/:testId/invoice- Generate invoice from test - POST
/api/v1/workspace/:workspaceId/labs/tests/:testId/income- Post test invoice to income - POST
/api/v1/workspace/:workspaceId/labs/tests/:testId/items/:itemId/interpret- Get AI interpretation for a test item
Features
- Test Units: Measurement units for lab test results (e.g., mg/dL, mmol/L, units/L)
- Analyses: Laboratory test definitions with pricing, units, and sample types
- Reference Ranges: Age and gender-based normal ranges with priority matching
- Conditional Result Notes: Notes displayed when results match specific conditions (
>=,<=,=,>,<) - Automatic Range Matching: Results automatically matched to appropriate ranges based on client age and gender
- Flag Computation: Automatic computation of result flags (normal, low, high) based on matched ranges
- AI Interpretation: OpenAI-powered interpretation of test results
- Invoicing Integration: Generate invoices from completed tests
- Income Integration: Post test invoices to income records
Permissions
labs.view: Required for viewing labs datalabs.manage: Required for creating/editing analyses, ranges, unitslabs.run: Required for creating tests and entering resultslabs.billing: Required for invoicing and posting to income
Request/Response Format
Create Analysis:
{
"testName": "Complete Blood Count",
"reportName": "CBC",
"billName": "CBC Test",
"price": 150,
"unitId": "unit-id"
}
Add Range:
{
"gender": "both",
"ageFrom": 0,
"ageTo": 100,
"ageUnit": "years",
"lowLimit": 0,
"highLimit": 50,
"resultNotes": [
{
"condition": ">=",
"value": 40,
"note": "High value detected"
}
],
"priority": 1
}
Create Test:
{
"clientId": "client-id",
"testDate": "2024-01-15T10:00:00Z",
"analysisIds": ["analysis-id-1", "analysis-id-2"]
}
Save Result:
{
"resultValueNumeric": 45.5
}
Related Documentation
- Labs API Endpoints - Complete Labs API documentation
Client Date of Birth and Gender Fields
Added: dateOfBirth and gender fields to client creation and update endpoints.
Updated Endpoints
- POST
/api/v1/workspace/:workspaceId/clients- Create client (now acceptsdateOfBirthandgender) - PATCH
/api/v1/workspace/:workspaceId/clients/:clientId- Update client (now acceptsdateOfBirthandgender)
New Fields
dateOfBirth(string, optional): Date of birth in ISO 8601 format (YYYY-MM-DD). Used for age-based features like Labs module.gender(string, optional): Gender. Valid values:'male','female'. Used for gender-specific features like Labs module.
Request Format
Create/Update Client:
{
"name": "John Doe",
"dateOfBirth": "1990-01-15",
"gender": "male",
"contactMethods": [...]
}
Use Cases
- Age calculation for Labs module reference range matching
- Gender-based filtering for Labs module reference ranges
- Client demographic data collection
Admin Workspace Subscription Management & Invoice Additions
Added: Enhanced subscription management endpoints for admin with invoice additions and additional storage control.
New Endpoints
Invoice Additions Management:
- GET
/api/v1/admin/workspaces/:workspaceId/invoice-additions- List all invoice additions for a workspace - POST
/api/v1/admin/workspaces/:workspaceId/invoice-additions- Create a new invoice addition - PATCH
/api/v1/admin/workspaces/:workspaceId/invoice-additions/:additionId- Update an invoice addition - DELETE
/api/v1/admin/workspaces/:workspaceId/invoice-additions/:additionId- Delete an invoice addition
Additional Storage Management:
- PATCH
/api/v1/admin/workspaces/:workspaceId/storage- Update additional storage for a workspace
Workspace Details:
- GET
/api/v1/admin/workspaces/:workspaceId- Enhanced response now includesadditionalStorageMBandinvoiceAdditionsfields
Features
-
Invoice Additions:
- Custom charges that are added to monthly invoice
- Each addition includes: reason, quantity, unit price, total (auto-calculated)
- Additions are NOT subject to workspace discount
- Full CRUD operations available
- Tracked with creation date and admin ID
-
Additional Storage:
- Add extra storage (in MB) beyond plan allocation
- Total storage quota = Plan storage + Additional storage
- Storage quota calculation automatically includes additional storage
- Real-time storage usage tracking
-
Subscription Renewal Integration:
- Subscription renewal calculation now includes invoice additions
- Total payment = (Plan price - discount) + Invoice additions total
- Invoice additions are added without discount application
Request/Response Format
Create Invoice Addition:
{
"reason": "Additional 1GB storage",
"quantity": 1,
"unitPrice": 2.00
}
Response:
{
"id": "addition-id",
"reason": "Additional 1GB storage",
"quantity": 1,
"unitPrice": 2.00,
"total": 2.00,
"createdAt": "2024-01-01T00:00:00.000Z",
"createdBy": "admin-id"
}
Update Additional Storage:
{
"additionalStorageMB": 1024
}
Workspace Response (Enhanced):
{
"id": "workspace-id",
"additionalStorageMB": 1024,
"invoiceAdditions": [
{
"id": "addition-id",
"reason": "Additional 1GB storage",
"quantity": 1,
"unitPrice": 2.00,
"total": 2.00,
"createdAt": "2024-01-01T00:00:00.000Z",
"createdBy": "admin-id"
}
],
"plan": {
"id": "plan-id",
"name": "Starter",
"pricePeriods": [
{
"period": "monthly",
"amountCents": 5000,
"currencyCode": "USD"
}
]
}
}
Authentication
- All endpoints require admin authentication
- Permission:
businesses.managerequired for all operations
Database Schema Changes
Workspace Model (Enhanced):
- Added
additionalStorageMB: Number(default: 0, min: 0) - Added
invoiceAdditions: Array<InvoiceAddition>(default: [])
InvoiceAddition Schema:
{
reason: String (required),
quantity: Number (required, min: 0.01),
unitPrice: Number (required, min: 0),
createdAt: Date (required),
createdBy: ObjectId (required, ref: 'Admin')
}
Integration Changes
Storage Quota Calculation:
getMaxStorageQuotanow includesadditionalStorageMBin calculation- Total quota = Plan maxstorage flag + Additional storage
Subscription Renewal:
renewSubscriptionnow calculates total from invoice additions- Payment amount = (Plan price × (1 - discount/100)) + Sum of invoice additions
Use Cases
- Custom Billing: Add custom charges for special services
- Storage Allocation: Provide additional storage to workspaces
- Flexible Pricing: Maintain custom charges while applying discounts
- Billing Transparency: Clear breakdown of all charges
Documentation
- List Invoice Additions - Workspace detail endpoint
- Product Changelog - Product feature documentation
Multi-Factor Authentication (MFA) System
Added: Complete multi-factor authentication system for admin and workspace accounts.
Admin MFA Endpoints
- POST
/api/v1/admin/mfa/totp/setup- Generate TOTP secret and QR code - POST
/api/v1/admin/mfa/totp/confirm- Confirm TOTP enrollment - POST
/api/v1/admin/mfa/verify- Verify MFA during login - GET
/api/v1/admin/mfa/status- Get MFA status
Workspace MFA Endpoints
Phone OTP:
- POST
/api/v1/workspace/mfa/phone/start- Start phone OTP enrollment - POST
/api/v1/workspace/mfa/phone/verify- Verify phone OTP enrollment
TOTP:
- POST
/api/v1/workspace/mfa/totp/setup- Generate TOTP secret and QR code - POST
/api/v1/workspace/mfa/totp/confirm- Confirm TOTP enrollment
Backup Codes:
- POST
/api/v1/workspace/mfa/backup-codes/generate- Generate backup codes - POST
/api/v1/workspace/mfa/backup-codes/regenerate- Regenerate backup codes - GET
/api/v1/workspace/mfa/backup-codes/count- Get remaining backup codes count
Methods Management:
- GET
/api/v1/workspace/mfa/methods- List enrolled MFA methods - PATCH
/api/v1/workspace/mfa/methods/:methodId/primary- Set primary method - DELETE
/api/v1/workspace/mfa/methods/:methodId- Disable MFA method
Authentication MFA:
- POST
/api/v1/auth/mfa/phone/send- Send OTP for login challenge - POST
/api/v1/auth/mfa/verify- Verify MFA challenge during login
Features
-
Admin MFA: TOTP-based authentication for admin accounts
-
Workspace MFA: Multiple methods for workspace owners:
- Phone OTP (SMS-based)
- TOTP (Authenticator apps)
- Backup Codes (Recovery codes)
-
Security Features:
- Encrypted secrets storage
- Challenge-based verification
- Replay attack protection
- Maximum attempt limits (5 per challenge)
- Challenge expiration
- Primary method selection
-
MFA Methods:
- Multiple methods can be enrolled
- One primary method per account
- Methods can be enabled/disabled
- Backup codes for account recovery
Use Cases
- Enhanced Security: Add extra layer of protection to accounts
- Compliance: Meet security requirements for sensitive operations
- Account Protection: Prevent unauthorized access even if password is compromised
- Flexible Authentication: Support different MFA methods based on user preference
Documentation
- Admin MFA API - Admin MFA endpoints
- Workspace MFA API - Workspace MFA endpoints
Recurring Expenses Management System
Added: Complete recurring expenses management system for workspace-level expense automation and tracking.
New Endpoints
Recurring Expense Rules:
- POST
/api/v1/client/workspace/:workspaceId/recurring-expense-rules- Create a new recurring expense rule - GET
/api/v1/client/workspace/:workspaceId/recurring-expense-rules- List recurring expense rules with filtering - GET
/api/v1/client/workspace/:workspaceId/recurring-expense-rules/:ruleId- Get a recurring expense rule by ID - PATCH
/api/v1/client/workspace/:workspaceId/recurring-expense-rules/:ruleId- Update a recurring expense rule - POST
/api/v1/client/workspace/:workspaceId/recurring-expense-rules/:ruleId/pause- Pause a recurring expense rule - POST
/api/v1/client/workspace/:workspaceId/recurring-expense-rules/:ruleId/resume- Resume a paused recurring expense rule - DELETE
/api/v1/client/workspace/:workspaceId/recurring-expense-rules/:ruleId- Delete a recurring expense rule
Recurring Expense Occurrences:
- GET
/api/v1/client/workspace/:workspaceId/recurring-expense-occurrences- List recurring expense occurrences with filtering - GET
/api/v1/client/workspace/:workspaceId/recurring-expense-occurrences/stats- Get occurrence statistics - GET
/api/v1/client/workspace/:workspaceId/recurring-expense-occurrences/:occurrenceId- Get an occurrence by ID - POST
/api/v1/client/workspace/:workspaceId/recurring-expense-occurrences/:occurrenceId/post- Post an occurrence (create expense and mark as posted) - POST
/api/v1/client/workspace/:workspaceId/recurring-expense-occurrences/:occurrenceId/skip- Skip an occurrence
Features
-
Recurring Expense Rules: Create rules for recurring expenses with:
- Frequencies: Daily, Monthly, Yearly
- Amount: Fixed amount per occurrence
- Scheduling: Start date, end date (optional), day of month (for monthly), month of year (for yearly)
- Metadata: Title, vendor, category, account, notes
- Status: Active or Paused
-
Automatic Occurrence Generation: System automatically generates expense occurrences based on rules:
- Daily: Creates occurrences every day from start date
- Monthly: Creates occurrences on specified day of month
- Yearly: Creates occurrences on specified month and day of year
-
Occurrence Management:
- Statuses: Upcoming, Pending, Posted, Skipped
- Post Occurrence: Convert occurrence to actual expense record
- Skip Occurrence: Mark occurrence as skipped without creating expense
- Custom Expense Date: Set custom date when posting occurrence
-
Advanced Filtering:
- Filter rules by status (active, paused) and frequency
- Filter occurrences by rule, date range, status, and frequency
- Pagination support for both rules and occurrences
-
Statistics: Comprehensive statistics including:
- Pending occurrences count and total amount
- Posted occurrences count and total amount
- Upcoming occurrences count and total amount
- Skipped occurrences count and total amount
Use Cases
- Rent Management: Automatically track monthly rent payments
- Subscription Tracking: Monitor recurring subscriptions (software, services)
- Utility Bills: Track monthly utility expenses
- Salary Payments: Automate salary expense tracking
- Annual Expenses: Track yearly expenses (insurance, licenses)
Documentation
- Recurring Expenses API endpoints (to be documented in workspace-financial section)
Workspace SMS Tracking
Added: Complete SMS tracking system for workspace-level SMS usage monitoring and payment management.
New Endpoints
- GET
/api/v1/workspace/sms/cost- Get SMS cost per message constant (public endpoint) - GET
/api/v1/workspace/:workspaceId/sms/summary- Get SMS usage summary (balance, total messages, total cost) - GET
/api/v1/workspace/:workspaceId/sms/messages- List SMS messages with filtering (type, status, pagination) - GET
/api/v1/workspace/:workspaceId/sms/payments- List SMS payments with pagination - POST
/api/v1/workspace/:workspaceId/sms/payments- Create a new SMS payment record - PATCH
/api/v1/workspace/:workspaceId/sms/payments/:paymentId- Update an SMS payment record - DELETE
/api/v1/workspace/:workspaceId/sms/payments/:paymentId- Delete an SMS payment record - POST
/api/v1/workspace/:workspaceId/sms/payments/:paymentId/receipt-image- Upload receipt image for SMS payment - DELETE
/api/v1/workspace/:workspaceId/sms/payments/:paymentId/receipt-image- Delete receipt image for SMS payment
Features
-
SMS Cost Tracking: Constant cost per message (currently $0.05)
-
Usage Summary: Real-time summary including:
- Current SMS balance
- Total messages sent
- Total cost incurred
- Remaining balance
- Minimum allowed balance threshold
-
Message Tracking: View all sent SMS messages with:
- Message type (OTP, notification, other)
- Delivery status (pending, sent, failed)
- Recipient information
- Message content
- Cost per message
- Timestamp
-
Payment Management: Track SMS payments/credits:
- Payment amount and method (cash, bank-transfer, card, other)
- Payment date and description
- Receipt image upload
- Payment history tracking
-
Balance Management:
- Balance can go negative up to minimum threshold (-$0.12)
- SMS sending disabled when balance is insufficient
- Low balance warnings
-
Advanced Filtering:
- Filter messages by type and status
- Pagination support for messages and payments
Authentication
- Most endpoints require workspace authentication (Workspace Owner or Staff with permissions)
/api/v1/workspace/sms/costis a public endpoint (no authentication required)
Documentation
- SMS Tracking API - Complete SMS tracking endpoints
Workspace Services & Multiple Services per Session
Updated: Workspace Services API and Sessions API to support multiple services per session with automatic duration calculation.
Workspace Services Changes
- Renamed: Services are now referred to as "Workspace Services" to clarify workspace context
- Added:
scopefield (required, default:"sessions") to define service usage within workspace - Updated: All service endpoints now include
scopefield in request/response - Query Parameter: Added
scopequery parameter to filter services by scope
Sessions Changes
- Breaking Change:
serviceId(single) changed toserviceIds(array) - Sessions now support multiple services - Added: Automatic duration calculation - Session duration is calculated from sum of selected services' durations
- Updated:
createSessionendpoint now acceptsserviceIdsarray (minimum 1 service required) - Updated:
updateSessionendpoint now acceptsserviceIdsarray for updating services - Updated:
listSessionsendpoint now supports filtering byserviceIds(comma-separated) - Response: Session objects now include
serviceIdsandserviceNamesarrays instead of singleserviceIdandserviceName - Duration:
durationMinutesis now optional in create/update - automatically calculated if not provided
Features
- Multiple Services: Select multiple services when creating or updating a session
- Auto Duration: System automatically calculates session duration from services
- Manual Override: Manual duration can be set, with warning if different from calculated
- Scope Filtering: Only services with
scope: "sessions"are available for session assignment - Backward Compatibility: System handles old sessions with single
serviceIdduring migration
Documentation
- Workspace Services API - Updated with scope field
- Create Session - Updated for multiple services
- Update Session - Updated for multiple services
- List Sessions - Updated response format
Payments Management System
Added: Complete unified payments management system for tracking all workspace payments.
New Endpoints
- GET
/api/v1/admin/payments- List all workspace payments with filtering and pagination - GET
/api/v1/admin/payments/stats- Get payment statistics (total, monthly, weekly, daily) - POST
/api/v1/admin/payments- Create a new manual payment record - PATCH
/api/v1/admin/payments/:paymentId- Update an existing manual payment - DELETE
/api/v1/admin/payments/:paymentId- Delete a manual payment record
Features
-
Payment Types: Supports four payment types:
ai-tools: Payments for AI tool usage and creditssms: Payments for SMS message creditsstorage: Payments for additional storage capacitysubscription: Payments for workspace subscription renewals
-
Payment Methods: Cash, bank transfer, card, and other payment methods
-
Automatic Payment Recording: System automatically creates payment records for:
- Subscription renewals (when workspace renews subscription)
- SMS payments (when admin adds SMS payment)
- AI tools payments (when admin adds AI tools payment)
-
Manual Payment Management: Admins can add, edit, and delete manual payments for offline transactions
-
Advanced Filtering: Filter by workspace, payment type, date range, and manual/automatic status
-
Statistics: Real-time statistics for total, monthly, weekly, and daily payments
Documentation
Expenses Management System
Added: Complete expenses management system for tracking platform operational costs.
New Endpoints
- GET
/api/v1/admin/expenses- List all platform expenses with filtering and pagination - GET
/api/v1/admin/expenses/stats- Get expense statistics with category breakdown - POST
/api/v1/admin/expenses- Create a new expense record - GET
/api/v1/admin/expenses/:expenseId- Get a single expense by ID - PATCH
/api/v1/admin/expenses/:expenseId- Update an existing expense - DELETE
/api/v1/admin/expenses/:expenseId- Delete an expense record - POST
/api/v1/admin/expenses/:expenseId/receipt- Upload a receipt image for an expense
Features
-
Expense Categories: Six predefined categories:
services: Service-related expensessalaries: Employee salaries and wagesrent: Office rent and facility costsutilities: Utility bills (electricity, water, internet)marketing: Marketing and advertising expensesother: Other miscellaneous expenses
-
Receipt Management: Upload and attach receipt images to expenses
-
Advanced Filtering: Filter by category and date range
-
Statistics: Comprehensive statistics with category breakdown:
- Total expenses (all time)
- This month's expenses
- This week's expenses
- Today's expenses
- Breakdown by category
Documentation
- List Expenses
- Get Expense Statistics
- Create Expense
- Get Expense
- Update Expense
- Delete Expense
- Upload Expense Receipt
Dashboard Enhancements
Updated: Admin dashboard endpoints with enhanced financial data.
Updated Endpoints
- GET
/api/v1/admin/dashboard/overview- Enhanced with payment and expense statistics - GET
/api/v1/admin/dashboard/revenue- New endpoint for detailed revenue, expenses, and net income
New Features
-
Payment Statistics: Dashboard overview now includes:
- Payment statistics (today, this week, this month)
- Revenue breakdown by payment type (AI tools, SMS, storage, subscription)
- Monthly recurring revenue (MRR)
-
Expense Statistics: Dashboard overview now includes:
- Expense statistics (today, this week, this month)
- Expense count and totals
-
Revenue Analysis: New revenue endpoint provides:
- Time-series breakdown of revenue and expenses
- Net income calculation (revenue - expenses)
- Support for multiple time periods (today, week, month, custom range)
- Detailed breakdown by time buckets
Documentation
Database Schema Changes
New Models
RecurringExpenseRule Model
{
workspaceId: ObjectId (required, indexed),
title: String (required),
amount: Number (required, min: 0),
currency: String (required, default: 'USD'),
categoryId: ObjectId (optional, nullable),
accountId: ObjectId (optional, nullable),
vendor: String (optional, nullable),
notes: String (optional, nullable),
frequency: 'daily' | 'monthly' | 'yearly' (required, indexed),
startDate: Date (required, indexed),
endDate: Date (optional, nullable),
dayOfMonth: Number (optional, nullable, min: 1, max: 31), // For monthly
monthOfYear: Number (optional, nullable, min: 1, max: 12), // For yearly
status: 'active' | 'paused' (required, default: 'active', indexed),
createdBy: ObjectId (required, indexed, ref: 'WorkspaceOwner'),
createdAt: Date (auto),
updatedAt: Date (auto)
}
RecurringExpenseOccurrence Model
{
workspaceId: ObjectId (required, indexed),
ruleId: ObjectId (required, indexed, ref: 'RecurringExpenseRule'),
dueDate: Date (required, indexed),
amount: Number (required, min: 0),
currency: String (required),
status: 'upcoming' | 'pending' | 'posted' | 'skipped' (required, indexed),
expenseId: ObjectId (optional, nullable, ref: 'Expense'), // When posted
postedBy: ObjectId (optional, nullable),
postedAt: Date (optional, nullable),
skippedAt: Date (optional, nullable),
createdAt: Date (auto),
updatedAt: Date (auto)
}
WorkspacePayment Model
{
workspaceId: ObjectId (required, indexed),
paymentType: 'ai-tools' | 'sms' | 'storage' | 'subscription' (required, indexed),
amount: Number (required, min: 0),
paymentMethod: 'cash' | 'bank-transfer' | 'card' | 'other' (required),
paymentDate: Date (required, indexed),
description: String (optional),
notes: String (optional),
isManual: Boolean (required, default: false),
createdBy: ObjectId (optional, ref: 'Admin'),
receiptImage: Object | null,
metadata: Object (optional),
createdAt: Date (auto),
updatedAt: Date (auto)
}
Expense Model
{
amount: Number (required, min: 0),
date: Date (required, indexed),
description: String (required),
category: 'services' | 'salaries' | 'rent' | 'utilities' | 'marketing' | 'other' (required, indexed),
receiptImage: Object | null,
notes: String (optional),
createdBy: ObjectId (required, ref: 'Admin'),
createdAt: Date (auto),
updatedAt: Date (auto)
}
Indexes Added
-
WorkspacePayment:
{ workspaceId: 1, paymentDate: -1 }{ workspaceId: 1, paymentType: 1 }{ paymentDate: -1 }{ paymentType: 1, paymentDate: -1 }
-
Expense:
{ date: -1 }{ category: 1, date: -1 }{ createdBy: 1, date: -1 }
-
RecurringExpenseRule:
{ workspaceId: 1, status: 1 }{ workspaceId: 1, frequency: 1 }{ workspaceId: 1, startDate: 1 }{ status: 1, startDate: 1 }
-
RecurringExpenseOccurrence:
{ workspaceId: 1, status: 1 }{ workspaceId: 1, dueDate: 1 }{ ruleId: 1, dueDate: 1 }{ status: 1, dueDate: 1 }
Integration Changes
Automatic Payment Creation
The system now automatically creates WorkspacePayment records when:
-
Subscription Renewal: When a workspace renews subscription via
/workspace/:workspaceId/subscription/renew- Calculates payment amount from plan price
- Applies workspace discount if available
- Records payment method
- Sets
isManual: false
-
SMS Payment: When admin adds SMS payment via SMS tracking service
- Creates both
SmsPaymentandWorkspacePayment - Links via
metadata.smsPaymentId - Sets
isManual: true
- Creates both
-
AI Tools Payment: When admin adds AI tools payment via AI tracking service
- Creates both
AiPaymentandWorkspacePayment - Links via
metadata.aiPaymentId - Sets
isManual: true
- Creates both
Authentication & Permissions
New Permissions
payments.view: Required to view payments list and statisticspayments.manage: Required to create, update, or delete paymentsdashboard.view: Required to view expenses (reuses existing permission)
Response Format Changes
Payment Response
All payment endpoints now return consistent response format with:
- Workspace information (id, name, email)
- Payment details (type, amount, method, date)
- Receipt image information (if available)
- Metadata for type-specific data
- Manual/automatic flag
Expense Response
All expense endpoints return:
- Expense details (amount, date, description, category)
- Receipt image information (if available)
- Creator information
- Timestamps
Breaking Changes
None. All changes are additive and backward compatible.
Migration Notes
For Existing Integrations
- No migration required for existing endpoints
- New endpoints are optional and can be integrated gradually
- Automatic payment creation is transparent and doesn't affect existing flows
For New Integrations
- Use the new unified payments endpoints for all payment tracking
- Use expenses endpoints for platform cost tracking
- Leverage dashboard endpoints for comprehensive financial overview
Future Enhancements
Planned improvements:
-
Payments:
- Export payments to CSV/Excel
- Payment reports and analytics
- Recurring payment management
- Payment reminders
- Integration with accounting systems
-
Expenses:
- Expense approval workflows
- Budget tracking
- Expense reports
- Category management
-
Dashboard:
- Advanced analytics and insights
- Custom date range comparisons
- Export capabilities
- Real-time updates
Version History
- v1.0.0 (Current): Initial release with payments and expenses management
- All endpoints follow v1 versioning policy (see API Intro)
Related Documentation
- API Introduction - General API information and versioning policy
- Admin Endpoints Index - Complete list of admin endpoints
- Payments Management (Product Docs) - Product documentation for payments feature