i have a project in odoo17 and fastapi, i need one feature, we need to send cancellation time dynamicly, i mean if cancellation time is set to 1890 seconds and user sent request after 1800 seconds we need to send 90 secods in the request: @router.get("/service/{service_id}", response_model=ServiceDetail)
async def get_service_detail(
service_id: int,
env: Annotated[Environment, Depends(odoo_env)]
):
"""
Get detailed information about a service by its ID.
"""
# Search for the service record by ID
service = env["msk.service"].sudo().search([("id", "=", service_id)], limit=1)
code
# If service is not found, raise a 404 HTTP exception
if not service:
raise HTTPException(status_code=404, detail="Service not found")
# Prepare the service detail data
return ServiceDetail(
id=service.id,
name=service.service_id.name if service.service_id else None,
opening_time=service.opening_time,
closing_time=service.closing_time,
price_for_call=service.price_for_call,
is_active=service.is_active,
cancellation_time=service.cancellation_time * 60,
description=service.description if service.description else None,
icon=get_media_url(service.service_id._name, service.service_id.id, 'icon') if service.service_id and service.service_id.icon else None,
image=get_media_url(service._name, service.id, 'image') if service.image else None
)
, ,from datetime import datetime
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
opening_time = fields.Char(string=_("Start time"), required=True)
opening_times = fields.Datetime(string=_("Start time"), required=True)
closing_time = fields.Char(string=_("End time"), required=True)
is_active = fields.Boolean(string=_("Is Active"), default=True,
help=_("If this service is not working, uncheck this field"))
description = fields.Text(string=_("Description"), required=True)
price_for_call = fields.Float(string=_("Price for call"), required=True)
cancellation_time = fields.Integer(string=_("Cancellation Time in Minutes"), required=True)
msk_id = fields.Many2one("res.users", string=_("MSK"), required=True)
service_id = fields.Many2one("service", string=_("Service"), required=True)
mahalla_id = fields.Many2one("mahalla", string=_("Mahalla"))
employee_ids = fields.Many2many("employee", "mahall_service_id", string=_("Employees"))
image = fields.Binary(string=_('Image'))
# Define a unique constraint
_sql_constraints = [
(
"msk_service_unique",
"unique(msk_id, service_id)",
"The combination of MSK and Service must be unique.",
)
]
@api.constrains("msk_id", "service_id")
def _check_unique_msk_service(self):
for record in self:
duplicate = self.search_count(
[
("msk_id", "=", record.msk_id.id),
("service_id", "=", record.service_id.id),
("id", "!=", record.id), # Exclude the current record
]
)
if duplicate:
raise ValidationError(
"The combination of MSK and Service must be unique."
)
@api.constrains("opening_time", "closing_time")
def _check_opening_closing_time(self):
time_format = "%H:%M" # 24-hour format: 'HH:MM'
for record in self:
try:
opening_time_obj = datetime.strptime(record.opening_time, time_format)
closing_time_obj = datetime.strptime(record.closing_time, time_format)
# Ensure opening time is before closing time
if opening_time_obj >= closing_time_obj:
raise ValidationError("Opening time must be before closing time.")
except ValueError:
raise ValidationError("Time must be in the format HH:MM (24-hour).")
# Ensure times are within the 24-hour range
if not (record.opening_time >= "00:00" and record.closing_time <= "23:59"):
raise ValidationError("Time must be within the range 00:00 to 23:59.")
@api.model
def create(self, vals):
# Set default msk_id to current user if not provided
if 'msk_id' not in vals:
vals['msk_id'] = self.env.user.id
return super(MskService, self).create(vals)
To implement a dynamic cancellation time feature in your Odoo 17 and FastAPI project, you'll need to calculate the remaining cancellation time based on when the service was requested and the predefined cancellation period. Here's a step-by-step guide on how to achieve this:
1. Understanding the Requirements
Cancellation Time: Defined in seconds (e.g., 1890 seconds).
Dynamic Calculation: If a user requests cancellation after a certain period (e.g., 1800 seconds), the API should return the remaining time (e.g., 90 seconds).
2. Assumptions
Start Time Reference: We'll use the create_date field provided by Odoo as the reference for when the service was created/requested. Alternatively, if you have a specific field like requested_at, you can use that instead.
Time Zones: Ensure all datetime objects are in UTC to avoid discrepancies.
3. Implementation Steps
a. Modify the FastAPI Endpoint
Update your FastAPI endpoint to calculate the remaining cancellation time dynamically. Here's how you can modify your existing /service/{service_id} endpoint:
python
from datetime import datetime, timezone
from fastapi import HTTPException, Depends
from typing import Annotated
from your_project.models import ServiceDetail # Adjust the import based on your project structure
@router.get("/service/{service_id}", response_model=ServiceDetail)
async def get_service_detail(
service_id: int,
env: Annotated[Environment, Depends(odoo_env)]
):
"""
Get detailed information about a service by its ID, including dynamic cancellation time.
"""
# Search for the service record by ID
service = env["msk.service"].sudo().search([("id", "=", service_id)], limit=1)
# If service is not found, raise a 404 HTTP exception
if not service:
raise HTTPException(status_code=404, detail="Service not found")
# Define the total cancellation time in seconds
total_cancellation_time = service.cancellation_time # Assuming it's already in seconds
# Get the current UTC time
now = datetime.now(timezone.utc)
# Retrieve the creation time of the service in UTC
creation_time = fields.Datetime.from_string(service.create_date)
if creation_time.tzinfo is None:
creation_time = creation_time.replace(tzinfo=timezone.utc)
else:
creation_time = creation_time.astimezone(timezone.utc)
# Calculate elapsed time in seconds
elapsed_time = (now - creation_time).total_seconds()
# Calculate remaining cancellation time
remaining_time = total_cancellation_time - elapsed_time
remaining_time = max(int(remaining_time), 0) # Ensure it's not negative
return ServiceDetail(
id=service.id,
name=service.service_id.name if service.service_id else None,
opening_time=service.opening_time,
closing_time=service.closing_time,
price_for_call=service.price_for_call,
is_active=service.is_active,
cancellation_time=remaining_time, # Dynamic cancellation time
description=service.description if service.description else None,
icon=get_media_url(service.service_id._name, service.service_id.id, 'icon') if service.service_id and service.service_id.icon else None,
image=get_media_url(service._name, service.id, 'image') if service.image else None
)
b. Ensure Correct Time Handling
Time Zones: Make sure that both creation_time and now are in the same timezone (preferably UTC) to avoid incorrect calculations.
Odoo create_date: This field typically stores the creation time of the record in UTC. However, it's good practice to confirm and handle timezones appropriately.
c. Update the ServiceDetail Pydantic Model
Ensure that your ServiceDetail Pydantic model is designed to accept the dynamic cancellation_time. Here's an example:
python
from pydantic import BaseModel
from typing import Optional
class ServiceDetail(BaseModel):
id: int
name: Optional[str]
opening_time: str
closing_time: str
price_for_call: float
is_active: bool
cancellation_time: int # Remaining time in seconds
description: Optional[str]
icon: Optional[str]
image: Optional[str]
class Config:
orm_mode = True
d. Handling Edge Cases
No Remaining Time: If the remaining time is zero or negative, you might want to handle this scenario differently, such as disabling the cancellation option on the frontend.
Service Already Canceled: If a service is already canceled or past the cancellation period, consider adding a status field or appropriate flags to indicate this.
4. Example Scenario
Let's walk through your example:
Cancellation Time Set: 1890 seconds (31.5 minutes).
User Requests After: 1800 seconds (30 minutes).
Calculation:
python
remaining_time = 1890 - 1800 # 90 seconds
The API will return cancellation_time as 90 seconds.
5. Additional Recommendations
Logging: Implement logging to monitor cancellation requests and remaining times for debugging and analytics.
Testing: Thoroughly test the endpoint with various scenarios to ensure accuracy, especially around time boundaries.
Caching: If the cancellation time doesn't need to be real-time, consider caching the response to reduce load, but ensure to invalidate the cache appropriately.
6. Complete FastAPI Endpoint with Imports
For clarity, here's the complete FastAPI endpoint with necessary imports:
python
from datetime import datetime, timezone
from fastapi import APIRouter, HTTPException, Depends
from typing import Annotated
from odoo.fields import Datetime
from your_project.dependencies import odoo_env, Environment # Adjust based on your project
from your_project.models import ServiceDetail # Adjust based on your project
router = APIRouter()
@router.get("/service/{service_id}", response_model=ServiceDetail)
async def get_service_detail(
service_id: int,
env: Annotated[Environment, Depends(odoo_env)]
):
"""
Get detailed information about a service by its ID, including dynamic cancellation time.
"""
# Search for the service record by ID
service = env["msk.service"].sudo().search([("id", "=", service_id)], limit=1)
# If service is not found, raise a 404 HTTP exception
if not service:
raise HTTPException(status_code=404, detail="Service not found")
# Total cancellation time in seconds
total_cancellation_time = service.cancellation_time * 60 # If stored in minutes
# Current UTC time
now = datetime.now(timezone.utc)
# Service creation time in UTC
creation_time = Datetime.from_string(service.create_date)
if creation_time.tzinfo is None:
creation_time = creation_time.replace(tzinfo=timezone.utc)
else:
creation_time = creation_time.astimezone(timezone.utc)
# Elapsed time in seconds
elapsed_time = (now - creation_time).total_seconds()
# Remaining cancellation time
remaining_time = total_cancellation_time - elapsed_time
remaining_time = max(int(remaining_time), 0) # Ensure non-negative
return ServiceDetail(
id=service.id,
name=service.service_id.name if service.service_id else None,
opening_time=service.opening_time,
closing_time=service.closing_time,
price_for_call=service.price_for_call,
is_active=service.is_active,
cancellation_time=remaining_time, # Dynamic value
description=service.description if service.description else None,
icon=get_media_url(service.service_id._name, service.service_id.id, 'icon') if service.service_id and service.service_id.icon else None,
image=get_media_url(service._name, service.id, 'image') if service.image else None
)
7. Conclusion
By calculating the remaining cancellation time dynamically based on the service's creation time and the predefined cancellation period, you provide a flexible and accurate way for users to understand their cancellation window. Ensure that all time calculations are consistent in terms of time zones and that edge cases are appropriately handled to maintain the integrity of your application.
If you have any further questions or need assistance with specific parts of the implementation, feel free to ask!