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)
discount = fields.Float(string=_("Discount"), defgault=0)
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",
"msk_service_employee_rel",
"msk_service_id",
"employee_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) add daterange to discount, and set it to 0 when time arrives, and add validations
To enhance your MskService model by adding a date range to the discount field, ensuring that the discount is automatically set to 0 once the end date is reached, and incorporating necessary validations, follow the steps below:
Add Date Range Fields for Discount:
discount_start_date: Specifies when the discount becomes active.
discount_end_date: Specifies when the discount expires.
Implement Validations:
Ensure that the discount_start_date is before or equal to the discount_end_date.
Optionally, ensure that the discount_end_date is not in the past when creating a new record.
Automate Discount Reset:
Create a scheduled action (cron job) that periodically checks for expired discounts and sets them to 0.
This involves adding a method in the model to perform the reset operation.
Fix Existing Code Issues:
Correct the typo in the discount field (defgault → default).
Remove any redundant fields if necessary (e.g., opening_times might be redundant if opening_time serves the purpose).
Below is the updated MskService model with the requested enhancements:
python
from datetime import datetime, date
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
class MskService(models.Model):
_name = "msk.service"
_description = _("Msk Service")
_rec_name = "service_id"
opening_time = fields.Char(string=_("Start Time"), required=True)
# Removed 'opening_times' as it seems redundant with 'opening_time'
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)
discount = fields.Float(
string=_("Discount"),
default=0.0,
help=_("Discount percentage or amount")
)
discount_start_date = fields.Date(
string=_("Discount Start Date"),
help=_("Date when the discount becomes active")
)
discount_end_date = fields.Date(
string=_("Discount End Date"),
help=_("Date when the discount expires")
)
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",
"msk_service_employee_rel",
"msk_service_id",
"employee_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 ("00:00" <= record.opening_time <= "23:59") or not ("00:00" <= record.closing_time <= "23:59"):
raise ValidationError("Time must be within the range 00:00 to 23:59.")
@api.constrains('discount_start_date', 'discount_end_date')
def _check_discount_dates(self):
for record in self:
if record.discount_start_date and record.discount_end_date:
if record.discount_start_date > record.discount_end_date:
raise ValidationError("Discount Start Date must be before or equal to Discount End Date.")
elif record.discount_start_date or record.discount_end_date:
raise ValidationError("Both Discount Start Date and Discount End Date must be set.")
@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)
@api.model
def update_expired_discounts(self):
"""
This method sets the discount to 0 for all services where the discount_end_date has passed.
It should be called periodically via a scheduled action (cron job).
"""
today = date.today()
expired_services = self.search([
('discount_end_date', '<', today),
('discount', '>', 0)
])
if expired_services:
expired_services.write({'discount': 0.0})
# Optionally, you can also clear the discount dates
# expired_services.write({'discount_start_date': False, 'discount_end_date': False})
Explanation of Enhancements
Added Date Range Fields:
python
discount_start_date = fields.Date(
string=_("Discount Start Date"),
help=_("Date when the discount becomes active")
)
discount_end_date = fields.Date(
string=_("Discount End Date"),
help=_("Date when the discount expires")
)
These fields allow you to specify the period during which the discount is active.
Validations for Date Range:
python
@api.constrains('discount_start_date', 'discount_end_date')
def _check_discount_dates(self):
for record in self:
if record.discount_start_date and record.discount_end_date:
if record.discount_start_date > record.discount_end_date:
raise ValidationError("Discount Start Date must be before or equal to Discount End Date.")
elif record.discount_start_date or record.discount_end_date:
raise ValidationError("Both Discount Start Date and Discount End Date must be set.")
Ensures that if either of the discount dates is set, both must be set.
Validates that the start date is not after the end date.
Automating Discount Reset:
python
@api.model
def update_expired_discounts(self):
"""
This method sets the discount to 0 for all services where the discount_end_date has passed.
It should be called periodically via a scheduled action (cron job).
"""
today = date.today()
expired_services = self.search([
('discount_end_date', '<', today),
('discount', '>', 0)
])
if expired_services:
expired_services.write({'discount': 0.0})
# Optionally, you can also clear the discount dates
# expired_services.write({'discount_start_date': False, 'discount_end_date': False})
Final Updated Model Code
Here is the complete updated msk_service model incorporating all the changes discussed:
python
Setting Up the Scheduled Action (Cron Job)
To ensure that expired discounts are reset automatically, you need to create a scheduled action that calls the update_expired_discounts method periodically. Here's how you can do it:
Create an XML File for the Scheduled Action:
Create a new XML file in your module's data directory (e.g., data/scheduled_actions.xml) with the following content:
model_id: References the msk.service model. Ensure that the XML ID model_msk_service correctly points to your model. If not, you might need to adjust it based on your module's configuration.
code: Specifies the method to call (update_expired_discounts).
interval_number & interval_type: Configured to run daily. Adjust as needed.
numbercall: -1 means the cron job will run indefinitely.
active: Ensures the cron job is active.
Include the XML File in Your Module's Manifest:
Update your __manifest__.py to include the new XML file:
python
# __manifest__.py
{
'name': "MSK Service",
# ... other metadata ...
'data': [
'data/scheduled_actions.xml',
# ... other data files ...
],
# ... rest of the manifest ...
}
Conclusion
With these enhancements, your MskService model now supports discount periods with automatic expiration handling. The scheduled action ensures that discounts are reset without manual intervention, maintaining data integrity and consistency.
Feel free to further customize the behavior, such as sending notifications when discounts expire or logging these events for audit purposes.
This method searches for all MskService records where the discount_end_date has passed and the discount is still active.
It sets the discount to 0.0 for these records.
Note: To ensure this method runs automatically, you need to set up a scheduled action (cron job) in Odoo.
Setting Up a Scheduled Action (Cron Job):
To automate the execution of the update_expired_discounts method, you need to create a scheduled action. This can be done via an XML data file or directly through the Odoo interface. Here's how you can define it in an XML file:
xml
<!-- Add this XML to your module's data files -->
<odoo>
<data noupdate="1">
<record id="ir_cron_update_expired_discounts" model="ir.cron">
<field name="name">Update Expired Discounts</field>
<field name="model_id" ref="model_msk_service"/>
<field name="state">code</field>
<field name="code">model.update_expired_discounts()</field>
<field name="interval_number">1</field>
<field name="interval_type">days</field>
<field name="numbercall">-1</field>
<field name="active">True</field>
</record>
</data>
</odoo>
Explanation:
interval_number: The number 1 combined with interval_typedays means the method will be called every day.
numbercall:-1 means the cron job will run indefinitely.
active: Set to True to activate the cron job.
Steps to Add the XML:
Create an XML file (e.g., data/scheduled_actions.xml) in your module.
Add the above XML content.
Reference this XML file in your module's __manifest__.py under the data key.
python
# __manifest__.py
{
'name': "MSK Service",
# ... other metadata ...
'data': [
'data/scheduled_actions.xml',
# ... other data files ...
],
# ... rest of the manifest ...
}
Upgrade your module to apply the changes.
Additional Recommendations:
Remove Redundant Fields: If opening_times (Datetime) is not necessary, consider removing it to avoid confusion since you already have opening_time (Char). Ensure that you use the appropriate field type for time-related fields (fields.Float for hour decimals, fields.Char with proper format, or fields.Time if using a custom widget).
Use fields.Float for Time if Needed: If you require precise time handling, consider using fields.Float to store time in decimal format (e.g., 9.5 for 9:30 AM).
Enhance User Interface: To provide a better user experience, consider adding widgets like calendar views or date pickers for date fields.
Logging and Notifications: Optionally, add logging to track when discounts are expired and reset, or notify users/admins about the changes.
from datetime import datetime, date
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
class MskService(models.Model):
_name = "msk.service"
_description = _("Msk Service")
_rec_name = "service_id"
opening_time = fields.Char(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)
discount = fields.Float(
string=_("Discount"),
default=0.0,
help=_("Discount percentage or amount")
)
discount_start_date = fields.Date(
string=_("Discount Start Date"),
help=_("Date when the discount becomes active")
)
discount_end_date = fields.Date(
string=_("Discount End Date"),
help=_("Date when the discount expires")
)
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",
"msk_service_employee_rel",
"msk_service_id",
"employee_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 ("00:00" <= record.opening_time <= "23:59") or not ("00:00" <= record.closing_time <= "23:59"):
raise ValidationError("Time must be within the range 00:00 to 23:59.")
@api.constrains('discount_start_date', 'discount_end_date')
def _check_discount_dates(self):
for record in self:
if record.discount_start_date and record.discount_end_date:
if record.discount_start_date > record.discount_end_date:
raise ValidationError("Discount Start Date must be before or equal to Discount End Date.")
elif record.discount_start_date or record.discount_end_date:
raise ValidationError("Both Discount Start Date and Discount End Date must be set.")
@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)
@api.model
def update_expired_discounts(self):
"""
This method sets the discount to 0 for all services where the discount_end_date has passed.
It should be called periodically via a scheduled action (cron job).
"""
today = date.today()
expired_services = self.search([
('discount_end_date', '<', today),
('discount', '>', 0)
])
if expired_services:
expired_services.write({'discount': 0.0})
# Optionally, clear the discount dates
# expired_services.write({'discount_start_date': False, 'discount_end_date': False})
Upgrade the Module:
After adding the XML file and updating the manifest, upgrade your module to apply the changes. You can do this via the command line or through the Odoo interface.
Command Line:
bash
odoo -u your_module_name -d your_database_name
Odoo Interface:
Navigate to Apps.
Click on Update Apps List.
Search for your module and click Upgrade.
Verify the Scheduled Action:
After upgrading, verify that the scheduled action has been created and is active:
Go to Settings > Technical > Automation > Scheduled Actions.