I was making a Odoo module today, it had a requirement to find the products that has offering within two ranges. Each of the product has different range for discounts/offers. It is sort of like the following:
For example, a shampoo discount starts from 01-06-2020 and ends at 20-06-2020, while another product like a soap discount starts from 10-06-2020 and ends at 22-06-2020. Now if I look for discounted credit notes to apply within a range, then we need to provide some time range, that these ranges intersect. For example, if I want to find discounts that were given within 02-06-2020 – 11 – 06 – 2020, then we should get both the discounts available here, as the discounts were still available for a day to the Soap and a few days for Shampoo. That means, we need to find if any of the given two ranges intersects with the ranges we have discounts for.
The easiest way to calculate this, is to check which date is max among the lower boundaries and which date is minimum in the lower boundaries. This should follow that the starting date would be less than or equal to the ending date, but never greater than the ending date. If greater than, then it does not intersect logically. In python, we can do this like the following:
# first we find all the vendor discounts, it has property start_date and end_date vendor_discounts = self.env['vendor.discount'].search([]) # list to keep the vendor discount instances vendor_discount_id_in_range = [] # from the form, we get date_from and date_to, where the dates intersect for vendor_discount in vendor_discounts: # here is the logic to find intersects if max(self.date_from, vendor_discount.start_date) <= min(self.date_to, vendor_discount.end_date): vendor_discount_id_in_range.append(vendor_discount.id)
So, the logic going to be like the following:
if max(input_date_from, start_date_to_match) <= min(input_date_to, end_date_to_match)